In Python, variables that are only referenced inside a function are implicitly global. If a variable is assigned a value anywhere within the function?s body, it?s assumed to be a local unless explicitly declared as global.
It can be a surprise to get the UnboundLocalError in previously working code when it is modified by adding an assignment statement somewhere in the body of a function.
>>> x = 10>>> def bar():… print(x)>>> bar()10
works, but this code:
>>> x = 10>>> def foo():… print(x)… x += 1
results in an UnboundLocalError:
>>> foo()Traceback (most recent call last): …UnboundLocalError: local variable ‘x’ referenced before assignment
This is because when you make an assignment to a variable in a scope, that variable becomes local to that scope and shadows any similarly named variable in the outer scope. Since the last statement in foo assigns a new value to x, the compiler recognizes it as a local variable. Consequently when the earlier print(x) attempts to print the uninitialized local variable and an error results.
In the example above you can access the outer scope variable by declaring it global:
>>> x = 10>>> def foobar():… global x… print(x)… x += 1>>> foobar()10
This explicit declaration is required in order to remind you that (unlike the superficially analogous situation with class and instance variables) you are actually modifying the value of the variable in the outer scope:
You can do a similar thing in a nested scope using the nonlocal keyword:
>>> def foo():… x = 10… def bar():… nonlocal x… print(x)… x += 1… bar()… print(x)>>> foo()1011
global : This keyword is useful when we need to assign any value to global object inside any function.
nonlocal : This keyword is useful when we need to assign any value to nested scope variable.
So friends, be little careful while playing with global object assignment in Python.
Happy Coding 🙂
Thanks for reading! If you liked this article, hit that clap button below ?. It means a lot to me and it helps other people see the story.