This issue tracker has been migrated to GitHub, and is currently read-only.
For more information, see the GitHub FAQs in the Python's Developer Guide.

classification
Title: Global variables and Local Variables with same name
Type: behavior Stage: resolved
Components: Versions: Python 2.7
process
Status: closed Resolution: not a bug
Dependencies: Superseder:
Assigned To: Nosy List: ezio.melotti, vijay_kansal
Priority: normal Keywords:

Created on 2014-03-14 07:23 by vijay_kansal, last changed 2022-04-11 14:57 by admin. This issue is now closed.

Messages (2)
msg213520 - (view) Author: VIJAY KANSAL (vijay_kansal) Date: 2014-03-14 07:23
Inside functions:
1. Python allows access to global variables.
2. 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:
1. Accessing global variable
2. 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 <module>
    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()
msg213521 - (view) Author: Ezio Melotti (ezio.melotti) * (Python committer) Date: 2014-03-14 07:35
This is by design, see http://docs.python.org/3/faq/programming.html#why-am-i-getting-an-unboundlocalerror-when-the-variable-has-a-value
History
Date User Action Args
2022-04-11 14:57:59adminsetgithub: 65121
2014-03-14 07:35:14ezio.melottisetstatus: open -> closed

nosy: + ezio.melotti
messages: + msg213521

resolution: not a bug
stage: resolved
2014-03-14 07:24:22vijay_kansalsettitle: Global variables -> Global variables and Local Variables with same name
2014-03-14 07:23:36vijay_kansalcreate