whjm whjm - 3 years ago 100
Python Question

`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 successfully so there are no problems with line #2 and line #3. But after I 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 it reports error so there must be something wrong with the uncommented line #4 but why the Traceback error is reported on line #2?

Answer Source

There is a answer in Programming FAQ

This is because when you make an assignment to a variable in a scope, that variable becomes local to that scope and shadows any similarly named variable in the outer scope.

Read complete here : Why am I getting an UnboundLocalError when the variable has a value?

When len is commented it is consider as a 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'>
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download