This question already has an answer here:
I am trying to figure out this:
c = 1
def f(n):
print c + n
def g(n):
c = c + n
f(1) => 2
g(1) => UnboundLocalError: local variable 'c' referenced before assignment
Thanks!
This question already has an answer here:
I am trying to figure out this:
c = 1
def f(n):
print c + n
def g(n):
c = c + n
f(1) => 2
g(1) => UnboundLocalError: local variable 'c' referenced before assignment
Thanks!
Within a function, variables that are assigned to are treated as local variables by default. To assign to global variables, use the
global
statement:This is one of the quirky areas of Python that has never really sat well with me.
Errata for Greg's post:
There should be no before they are referenced. Take a look:
It explodes, even if x is assigned after it's referenced. In Python variable can be local or refer outer scope, and it cannot change in one function.
Other than what Greg said, in Python 3.0, there will be the nonlocal statement to state "here are some names that are defined in the enclosing scope". Unlike global those names have to be already defined outside the current scope. It will be easy to track down names and variables. Nowadays you can't be sure where "globals something" is exactly defined.
Global state is something to avoid, especially needing to mutate it. Consider if
g()
should simply take two parameters or iff()
andg()
need to be methods of a common class withc
an instance attributeOutputs: