Namespaces are one honking great idea — let’s do more of those! Namespaces are the constructs used for organizing the names assigned to the objects in a python program. In this article, we will understand the concept of names and namespace in python.
What is a name in Python?
A name or identifier is the name given to objects when we create objects in python.
The name is simply the variable name that we use in our programs. In python, we can declare variable names and assign them to the objects as follows.
myInt = 1117
myString = "PythonForBeginners"
Here, we have defined two variables having names myInt and myString, which point to an integer an a string object respectively.
What is a namespace?
In simple words, A namespace is a collection of names and the details of the objects referenced by the names. We can consider a namespace as a python dictionary which maps object names to objects. The keys of the dictionary correspond to the names and the values correspond to the objects in python.
In python, there are four types of namespaces, namely built-in namespaces,global namespaces, local namespaces and enclosing namespaces. We will study about each of them in the following sections.
What is a built-in namespace in Python?
A built-in namespace contains the names of built-in functions and objects. It is created while starting the python interpreter, exists as long as the interpreter runs, and is destroyed when we close the interpreter. It contains the names of built-in data types,exceptions and functions like print() and input(). We can access all the names defined in the built-in namespace as follows.
builtin_names = dir(__builtins__)
for name in builtin_names:
print(name)
Output:
ArithmeticError
AssertionError
AttributeError
BaseException
BlockingIOError
BrokenPipeError
BufferError
BytesWarning
ChildProcessError
ConnectionAbortedError
ConnectionError
ConnectionRefusedError
ConnectionResetError
DeprecationWarning
EOFError
Ellipsis
EnvironmentError
Exception
False
FileExistsError
FileNotFoundError
FloatingPointError
FutureWarning
GeneratorExit
IOError
ImportError
ImportWarning
IndentationError
IndexError
InterruptedError
IsADirectoryError
KeyError
KeyboardInterrupt
LookupError
MemoryError
ModuleNotFoundError
NameError
None
NotADirectoryError
NotImplemented
NotImplementedError
OSError
OverflowError
PendingDeprecationWarning
PermissionError
ProcessLookupError
RecursionError
ReferenceError
ResourceWarning
RuntimeError
RuntimeWarning
StopAsyncIteration
StopIteration
SyntaxError
SyntaxWarning
SystemError
SystemExit
TabError
TimeoutError
True
TypeError
UnboundLocalError
UnicodeDecodeError
UnicodeEncodeError
UnicodeError
UnicodeTranslateError
UnicodeWarning
UserWarning
ValueError
Warning
ZeroDivisionError
__build_class__
__debug__
__doc__
__import__
__loader__
__name__
__package__
__spec__
abs
all
any
ascii
bin
bool
breakpoint
bytearray
bytes
callable
chr
classmethod
compile
complex
copyright
credits
delattr
dict
dir
divmod
enumerate
eval
exec
exit
filter
float
format
frozenset
getattr
globals
hasattr
hash
help
hex
id
input
int
isinstance
issubclass
iter
len
license
list
locals
map
max
memoryview
min
next
object
oct
open
ord
pow
print
property
quit
range
repr
reversed
round
set
setattr
slice
sorted
staticmethod
str
sum
super
tuple
type
vars
zip
In the above example, we can see that there are 152 names defined in built-in namespace for python 3.8 .
What is a global namespace in python?
Global namespaces are defined at the program or module level. It contains the names of objects defined in a module or the main program. A global namespace is created when the program starts and exists until the program is terminated by the python interpreter. The concept of a global namespace can be understood from the following example.
myNum1 = 10
myNum2 = 10
def add(num1, num2):
temp = num1 + num2
return temp
In the example above, myNum1 and myNum2 are in the global namespace of the program.
What is a local namespace in Python?
A local namespace is defined for a class, a function, a loop, or any block of code. The names defined in a block of code or a function are local to it. The variable names cannot be accessed outside the block of code or the function in which they are defined. The local namespace is created when the block of code or the function starts executing and terminates when the function or the block of code terminates. The concept of the local namespace can be understood from the following example.
myNum1 = 10
myNum2 = 10
def add(num1, num2):
temp = num1 + num2
return temp
Here, the variable names num1, num2 and temp are defined in the local namespace in the function add.
What is an enclosing namespace?
As we know that we can define a block of code or a function inside another block of code or function, A function or a block of code defined inside any function can access the namespace of the outer function or block of code. Hence the outer namespace is termed as enclosing namespace for the namespace of the inner function or block of code. This will be more clear from the following example.
myNum1 = 10
myNum2 = 10
def add(num1, num2):
temp = num1 + num2
def print_sum():
print(temp)
return temp
In the above example, the local namespace of add() function is the enclosing namespace of the print_sum() function as print_sum() is defined inside the add() function.
Conclusion
In this article, we have discussed names and namespaces in python. We have also seen different types of namespaces and their functioning. You may read this article on list comprehension. Stay tuned for more informative articles.
Recommended Python Training
Course: Python 3 For Beginners
Over 15 hours of video content with guided instruction for beginners. Learn how to create real world applications and master the basics.