python - `UnboundLocalError` reported on wrong line number -


for example:

$ cat -n foo.py      1  def f():      2      str = len      3      str = str('abc')      4  #   len = len('abc')      5  f() $ python2.7 foo.py $ 

it runs there no problems line #2 , line #3. after uncomment line #4:

$ cat -n bar.py      1  def f():      2      str = len      3      str = str('abc')      4      len = len('abc')      5  f() $ python2.7 bar.py traceback (most recent call last):   file "bar.py", line 5, in <module>     f()   file "bar.py", line 2, in f     str = len unboundlocalerror: local variable 'len' referenced before assignment $ 

now reports error there must wrong uncommented line #4 why traceback error reported on line #2?

there answer in programming faq

this because when make assignment variable in scope, variable becomes local scope , shadows named variable in outer scope.

read complete here : why getting unboundlocalerror when variable has value?

when len commented consider build in function len()

def f():     str = len     print type(str)     str = str('abc')     # len = len('abc')     print type(len)  f()  <type 'builtin_function_or_method'> <type 'builtin_function_or_method'> 

Comments

Popular posts from this blog

python - Selenium remoteWebDriver (& SauceLabs) Firefox moseMoveTo action exception -

html - How to custom Bootstrap grid height? -

transpose - Maple isnt executing function but prints function term -