Possible Duplicate:
Short Description of Python Scoping Rules
I wrote two simple functions:
# coding: utf-8
def test():
var = 1
def print_var():
print var
print_var()
print var
test()
# 1
# 1
def test1():
var = 2
def print_var():
print var
var = 3
print_var()
print var
test1()
# raise Exception
In comparison, test1() assigns value after print var, then raise an Exception: UnboundLocalError: local variable 'var' referenced before assignment, I think the moment I call inner print var, var has a value of 2, am I wrong?
asked Sep 12, 2012 at 6:39
iMom0
13k3 gold badges52 silver badges61 bronze badges
1 Answer 1
Yes, you're incorrect here. Function definition introduces a new scope.
# coding: utf-8
def test():
var = 1
def print_var():
print var <--- var is not in local scope, the var from outer scope gets used
print_var()
print var
test()
# 1
# 1
def test1():
var = 2
def print_var():
print var <---- var is in local scope, but not defined yet, ouch
var = 3
print_var()
print var
test1()
# raise Exception
answered Sep 12, 2012 at 6:43
wim
369k114 gold badges682 silver badges821 bronze badges
Sign up to request clarification or add additional context in comments.
7 Comments
Lauritz V. Thaulow
Hang on, I thought python did not look ahead when executing. How does python know that
var is going to be a local variable in the second print_var function?Lauritz V. Thaulow
So when python parses the function it saves a list of the names of all variables that are assigned to within. Then at call time it sees that
var is in this list, and complains since it's not defined yet. Is this local variable list accessible?Martijn Pieters
@lazyr: Exactly; variables are bound to a scope at compile time. Assignment is a storing operation, and binds that variable to the local scope unless marked global. If there is no assignment, the variable is 'free' and looked up in surrounding scopes, but this is bound as well to that specific scope. See Python nested scopes with dynamic features for example.
Lauritz V. Thaulow
@Martijn Can I access the scope of a function and see what its local variables are called?
Martijn Pieters
@lazyr: Yes, see docs.python.org/reference/datamodel.html,
afunction.func_code.co_varnames are local variables. co_freevars and co_cellvars are interesting in this respect; they are variables taken from the surrounding scope (non-global) and variables referred to by nested functions, respectively. |
lang-py
globaldeclaration would not help here, asvaris a function-scope variable. In python 3 you'd usenonlocalbut in python 2 (as used here) there is no way you can do what the OP is trying to do.