When a reference variable is made inside a function, the name is searched in the local namespace first, then in the global namespace and finally in the built-in namespace.
- In Python, a variable declared outside of the function or in global scope is known as global variable.
- This means, global variable can be accessed inside or outside of the function.
x = “global”
print(“x inside :”, x)func()
Global Variables Across Python Modules:
- In Python, we create a single module config.py to hold global variables and share information across Python modules within the same program.
- Here is how we can share global variable across the python modules.
- Create a config.py file, to store global variables
a = 0
b = “empty”
- Create a update.py file, to change global variables
config.a = 10
config.b = “Python”
- Create a main.py file, to test changes in value
- When we run the main.py file, the output will be
Global in Nested Functions:
x = 20
x = 25
print(“Before calling bar: “, x)
print(“Calling bar now”)
print(“After calling bar: “, x)
print(“x in main : “, x)
y = “local”
- A function defined inside another function is called a nested function. Nested functions can access variables of the enclosing scope.
- In Python, these non-local variables are read only by default and we must declare them explicitly as non-local (using nonlocal keyword) in order to modify them.
- Following is an example of a nested function accessing a non-local variable.
- We can see that the nested function printer() was able to access the non-local variable msg of the enclosing printmsg() function.
- This means, the variable can be neither in the local nor the global scope.
- We use nonlocal keyword to create nonlocal variable.