Organize Code
Namespace
Python
# myproject/Greeting.py
def greet():
print('Hi!')
Namespaces are used to avoid conflicting definitions and introduce more flexibility and organization in the codebase.
There are no special keywords for defining Namespaces in Python, But Python has its own way of handling and organizing conflicting names.
Each module creates its own global namespace.
a = 11
def outer():
a = 12
def inner():
print(a) # 12
inner()
print(a) # 12
outer()
print(a) # 11
Namespaces in python are created and handled differently compare to other Programming Languages.
In Python Namespaces and Scopes have a close relation.
There 3 types of namespaces in Python:
- Built-in: highest level namespace
- Global: module-level namespace
- Local: function or class level namespace
On each function call, a local namespace is created.
When a name (variable or function) is tried to be read, Python engine:
- checks the local namespaces in order.
- checks global namespace.
- at last checks the built-in namespace.
a = 11
def outer():
a = 12
def inner():
a = 13
print(a) # 13
inner()
print(a) # 12
outer()
print(a) # 11
On the other hand, if you try to set a name (set a variable or define function) it will always create it in the last Local Namespace unless you specified that name using the global
keyword.