Python scope: “UnboundLocalError: local variable ‘c’ referenced before assignment”

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!

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

Within a function, variables that are assigned to are treated as local variables by default. To assign to global variables, use the global statement:

def g(n):
    global c
    c = c + n

This is one of the quirky areas of Python that has never really sat well with me.

Method 2

Global state is something to avoid, especially needing to mutate it. Consider if g() should simply take two parameters or if f() and g() need to be methods of a common class with c an instance attribute

class A:
    c = 1
    def f(self, n):
        print self.c + n
    def g(self, n):
        self.c += n

a = A()
a.f(1)
a.g(1)
a.f(1)

Outputs:

2
3

Method 3

Errata for Greg’s post:

There should be no before they are referenced. Take a look:

x = 1
def explode():
    print x # raises UnboundLocalError here
    x = 2

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.

Method 4

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.


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x