python question on scope and variables - not sure how this variable is defined and the technique used

11 Views Asked by At

I came across this code snipped on decorators which I am reading about:

def call_counter(func):
    def helper(x):
        helper.calls += 1
        return func(x)
    helper.calls = 0

    return helper

@call_counter
def succ(x):
    return x + 1

print(succ.calls)
for i in range(10):
    succ(i)
    
print(succ.calls)

I am a little puzzled how the variable

succ.calls

comes into this. How is it defined, what is the scope of this variable? To me it looks related to the function

succ

but it is not defined there, it seems defined in the function

helper

I tried something similar with:

def do_something():
    do_something.my_var = 6
    
print(do_something.my_var)   

as expected there are attribute errors. Thanks for any advice.

I am uncertain what this python technique is called so am unable to look it up.

0

There are 0 best solutions below