- Local
- Global
- Built-in
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.
Global Variables
- 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.
Example:
x = “global”
def func():
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.
Example:
- Create a config.py file, to store global variables
a = 0
b = “empty”
- Create a update.py file, to change global variables
import config
config.a = 10
config.b = “Python”
- Create a main.py file, to test changes in value
import config
import update
print(config.a)
print(config.b)
- When we run the main.py file, the output will be
10
Python
Global in Nested Functions:
def func():
x = 20
def bar():
global x
x = 25
print(“Before calling bar: “, x)
print(“Calling bar now”)
bar()
print(“After calling bar: “, x)
print(“x in main : “, x)
def myfunc():
y = “local”
print(y)
myfunc()
- 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.
def printer():
print(msg)
printer()
- 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.
Example: