Issue 20922: Global variables and Local Variables with same name (original) (raw)
Inside functions:
- Python allows access to global variables.
- Python allows creation of local variable with the same name as that of of some of the global variable.
Keeping the above two statements in mind, I believe that Python must allow following sequential statements in a function:
- Accessing global variable
- Creating local variable with the same name as that of some of the global variable name.
But, it seems that the above is not allowed. The below code has the following output:
Printing: 12 Throwing Error: Traceback (most recent call last): File "./bug.py", line 14, in func2() File "./bug.py", line 9, in func2 print 'Throwing Error: ', var UnboundLocalError: local variable 'var' referenced before assignment
CODE:
var = 12
def func1(): print 'Printing: ', var
def func2(): print 'Throwing Error: ', var var = 10 print 'Unreachable Code: ', var
func1() func2()