UnboundLocalError in Python

Sambhav Dave
Analytics Vidhya
Published in
3 min readMar 23, 2020

It is very irritating when a code that ran smoothly minutes ago, stocks due to a stupid mistake and hence, shows an error that is popular or rather common among Python developers called “UnboundLocalError”.

This story or rather a blog post by me, describes the nature of this error by seeing HOW it occurs, WHY it occurs & how you should SOLVE to remove it.

The HOW?

Consider the snippet below:

Smooth Case

In the snippet in the above screenshot, the value of num is 4 initially (treated as globally in Python because it is declared outside the method). In the method named myFunc(), we are simply printing its value. So the output is:

Smooth Case (Result)

Now, let us modify the above smooth case, and let’s face the problem. Consider the snippet below:

Problematic Case

Do note here that, we first are planning to print the value of num and then modify its value to let’s say 8 (line 6). Let’s run the code again by calling the function myFunc() as before.

Problematic Case (Result)

It can be easily seen that the whole subject of this post is visible in the error above, the UnboundLocalError. Let’s understand the reason behind it by going through the more interesting WHY section…

The WHY?

This error arises due to a minor fault of scope. In python, all the variables inside a function are global if they are not assigned any value to them.

That means if a variable is only referenced outside a function, it is global. However, if we assign any value to a variable inside a function, its scope becomes local to that unless explicitly declared global.

In the first example (smooth case), we are not assigning any value to the x variable inside the function and just referencing it to print. Hence x is global.

In the second example (problematic case), we assigned the value 8 to x, hence x’s scope is local to function and we tried to print it before assigning any value to x.

The SOLUTION ! :)

You would need to use the keyword global before modifying it inside the function as shown below.

Smooth Again!

Focus on line 5 where we have put the keyword global to tell the Python interpreter that, whatever change is being done ahead of this point to the value of num, reflects its global value. In other words, change it for every other occurrence of num. And that’s it. Done.

There is one more solution to it, i.e. by using nonlocal keywords, but that is generally not advisable. Hence, I haven’t discussed it over here.

I hope this simple amateur post created some interest for those starting off with Python (like me) and for those who have faced this error. Stay tuned for many such posts related to Python programming. I’ll try being an active part of the Medium community.

Thanks for reading!

Cheers!!

--

--

Sambhav Dave
Analytics Vidhya

Senior Automation Test Engineer @ Xogene Services LLC