In Python, how can I use a function attribute as a function?

154 Views Asked by At

In Python, you could define a function attribute "call_count" such that:

def counter(func):
    def inner(*args):
        inner.call_count+= 1
        return func(*args)

    inner.call_count= 0
    return inner

def sum(a, b, c):
    return a+b+c

sumCounter= counter(sum)

print(sumCounter(1,2,3))
print(sumCounter.call_count)

print(sumCounter(3,2,2))
print(sumCounter.call_count)

This prints:

6
1
7
2

What if, instead of being able to call sumCounter.call_count, I'd want to call a function attribute sumCounter.call_count()? That is, a function attribute that "looks" like a class method? How could this be done?

2

There are 2 best solutions below

0
Frank Yellin On

You can either have a variable named call_count or a function named call_count, but not both. And in either case, you do need some variable.

def counter(func):
    def inner(*args):
        inner._call_count+= 1
        return func(*args)

    inner._call_count= 0
    inner.call_count = lambda: _call_count
    return inner
0
sytech On

Functions are first class objects. They work just like instances of any class (because they are an instance of a class). You can assign any attributes to them, including other functions.

def counter(func):
    def inner(*args):
        inner._call_count+= 1
        return func(*args)
    
    inner._call_count= 0
    def call_count():
        return inner._call_count
    inner.call_count = call_count
    return inner