Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UnboundLocalError when manipulating variables yields inconsistent behavior

Tags:

python

scope

In Python, the following code works:

a = 1
b = 2

def test():
    print a, b

test()

And the following code works:

a = 1
b = 2

def test():
    if a == 1:
        b = 3
    print a, b

test()

But the following does not work:

a = 1
b = 2

def test():
    if a == 1:
        a = 3
    print a, b

test()

The result of this last block is an UnboundLocalError message, saying a is referenced before assignment.

I understand I can make the last block work if I add global a in the test() definition, so it knows which a I am talking about.

Why do I not get an error when assigning a new value to b?

Am I creating a local b variable, and it doesn't yell at me because I'm not trying to reference it before assignment?

But if that's the case, why can I print a, b in the case of the first block, without having to declare global a, b beforehand?

like image 970
ryantuck Avatar asked Dec 29 '25 13:12

ryantuck


2 Answers

Let me give you the link to the docs where it is clearly mentioned.

If a variable is assigned a new value anywhere within the function’s body, it’s assumed to be a local.

(emphasis mine)

Thus your variable a is a local variable and not global. This is because you have a assignment statement,

a = 3

In the third line of your code. This makes a a local variable. And referring to the local variable before declaration causes an error which is an UnboundLocalError.

However in your 2nd code block, you do not make any such assignment statements and hence you do not get any such error.

Another use ful link is this

Raised when a reference is made to a local variable in a function or method, but no value has been bound to that variable.

Thus you are referring to the local variable you create in the next line.

To prevent this there are two ways

  • Good way - Passing parameters

    Define your function as def test(a): and call it as test(a)

  • Bad way - Using global

    Have a line global a at the top of your function call.

Python scoping rules are a little tricky! You need to master them to get hold of the language. Check out this

like image 60
Bhargav Rao Avatar answered Jan 01 '26 03:01

Bhargav Rao


In the third block the compiler has marked a as a local variable since it is being assigned to, therefore when it is used in the expression it is looked for in the local scope. Since it does not exist there, an exception is raised.

In the second block the compiler has marked b as a local variable but not a, hence there is no exception when a is accessed since outer scopes will be searched.

like image 29
Ignacio Vazquez-Abrams Avatar answered Jan 01 '26 02:01

Ignacio Vazquez-Abrams



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!