0

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.

mkrieger1
  • 19,194
  • 5
  • 54
  • 65
  • What you tried last failed because the line `do_something.my_var = 6` was never executed, because you never called `do_something`. – mkrieger1 May 18 '23 at 11:07
  • `succ.calls` is `helper.calls = 0`, because `succ` refers to `return helper`. The decorated function *becomes* what the decorator returns. – deceze May 18 '23 at 11:18

0 Answers0