1

I have the following code

from time import sleep
def dec(my_func,*args,**kwargs):
     counter = 0
     def temp_func(*args, **kwargs):
         try:
             my_func(*args,**kwargs)
             return True
         except:
             if counter < 5:
                 counter+=1
                 temp_func(*args, **kwargs)
                 sleep(10)
             else:
                 return False
     return temp_func
@dec
def my_func(a,b):
    return a/b

print(my_func(1,2))
print(my_func(1,0))

Its throwing the following error.

---------------------------------------------------------------------------
UnboundLocalError                         Traceback (most recent call last)
<ipython-input-11-f73a2a9ab2e3> in <module>()
----> 1 my_func(1,0)

<ipython-input-8-bce781eec53d> in temp_func(*args, **kwargs)
      7             return True
      8         except:
----> 9             if counter < 5:
     10                 counter+=1
     11                 temp_func(*args, **kwargs)

UnboundLocalError: local variable 'counter' referenced before assignment

Why is the inner function not able to access decorator variable here? Usually, inner function has access to decorator variable. Even if i set counter variable in global context, i get the same error. Am i missing something here?

petezurich
  • 9,280
  • 9
  • 43
  • 57
rawwar
  • 4,834
  • 9
  • 32
  • 57

1 Answers1

0

I'm not entirely sure why this error happens, but if you move counter to temp_func instead of dec then it works. It should have the same effect.

Levi Lesches
  • 1,508
  • 1
  • 13
  • 23