Please check part-1 to get an understanding on the available scopes in python. Now let’s check how these various scopes work together in tandem
Global Scope vs Local Scope
Since ‘a’ can be accessed inside the function, lets change its value
As per the Global scope rules, variable ‘a’ should be accessible inside the function f1(). Infact we are able to print its value in this snippet (Fig 1). However the moment, there is a new value assigned to the variable, python compiler throws ‘local variable referenced before assignment’
This is happening because scope hierarchy is coupled with assignment rules
The moment we try to assign a value to ‘a’ inside the function, Python interpreter treats it as ‘local’ variable and since its previous value is not available (Python: No seperate declaration and only value assignment is available), it throws error
How to fix this? Use ‘global’ keyword to declare the variable inside a function
In the above code snippet, the value of ‘a’ is changed inside the function
Creating a new global variable inside a function
Python also gives provision to create a new global variable from inside a function. ‘global’ keyword can be used for this purpose as well
Local vs Enclosed Space
In the above code snippet:
func1(): ‘a’ is a local variable
nest1(): Python interpreter sees the assignment of ‘a’ without any tag. Which makes it to treat it ‘a’ as local variable for the function nest1() than treating it as the variable in the enclosed space. That is the reason even after calling nest1(), value of ‘a’ in func1() is still 10, rather than 20
How to change this behavior?
By adding the ‘nonlocal’ keyword before ‘a’ enables python interpreter to search in the enclosing space rather than the function local space
Can we create a new nonlocal variable (similar to global variable creation)?
Unlike ‘global’ keyword, ‘nonlocal’ keyword cannot be used to create new non-local variables. This keyword can only be used to access the already available variables in the enclosing space. Why?
That’s how Python defined non-local and global :)
Global vs Enclosed
In the above code snippet, ‘global’ scope for ‘a’ is defined in func1(). When nest1() encounters assignment of ‘a’, it will be treated as local variable for the function nest1() and its scope will be over once the control exits this function. Hence the reason for ‘a’ value not getting updated. How to fix this?
Global vs Enclosed vs Local Space
Over-riding built-in scope
What can be tried further?
- Inside func1(): Try using ‘nonlocal’ rather than ‘global’ and check the behaviour
- Inside func1(): Create a local variable with same name as global variable and try to modify its value inside nested function using ‘global’, ‘nonlocal’ keywords
- How to get back the built-in functionality after over-riding
Please also let me know, if you find any other behaviours apart from the things we have discussed in the two parts. ~~