- Namespaces and Scope in Python
- Types of namespaces :
- The lifetime of a namespace :
- What is Namespace in Python?
- What is a name in Python?
- What is a namespace?
- What is a built-in namespace in Python?
- What is a global namespace in python?
- What is a local namespace in Python?
- What is an enclosing namespace?
- Conclusion
- Related
- Recommended Python Training
- Namespace and Scope in Python
- Introduction
- What are Namespace and Scope?
- Types of Namespaces
- Global Namespace
- Local Namespace
- Built-in
- Examples
- Example 1 – Behavior of local variables
- Example 2 – Using global variables within functions
Namespaces and Scope in Python
A namespace is a system that has a unique name for each and every object in Python. An object might be a variable or a method. Python itself maintains a namespace in the form of a Python dictionary. Let’s go through an example, a directory-file system structure in computers. Needless to say, that one can have multiple directories having a file with the same name inside every directory. But one can get directed to the file, one wishes, just by specifying the absolute path to the file.
Real-time example, the role of a namespace is like a surname. One might not find a single “Alice” in the class there might be multiple “Alice” but when you particularly ask for “Alice Lee” or “Alice Clark” (with a surname), there will be only one (time being don’t think of both first name and surname are same for multiple students).
On similar lines, the Python interpreter understands what exact method or variable one is trying to point to in the code, depending upon the namespace. So, the division of the word itself gives a little more information. Its Name (which means name, a unique identifier) + Space(which talks something related to scope). Here, a name might be of any Python method or variable and space depends upon the location from where is trying to access a variable or a method.
Types of namespaces :
When Python interpreter runs solely without any user-defined modules, methods, classes, etc. Some functions like print(), id() are always present, these are built-in namespaces. When a user creates a module, a global namespace gets created, later the creation of local functions creates the local namespace. The built-in namespace encompasses the global namespace and the global namespace encompasses the local namespace.
The lifetime of a namespace :
A lifetime of a namespace depends upon the scope of objects, if the scope of an object ends, the lifetime of that namespace comes to an end. Hence, it is not possible to access the inner namespace’s objects from an outer namespace.
What is Namespace in Python?
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)
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.
Related
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.
Namespace and Scope in Python
The concept of Namespaces and Scope helps us identify variable hierarchy in python, with which we can understand variable behaviour.
Programming without these concepts could be be problematic as unwanted variables can get modified during execution, or we may end up accessing variables outside their scope.
With Namespaces we can make sense of the priority given to variables with the same name, and with Scope we can identify the effective ‘lifespan’ of a variable, both of which will help in writing lucid python code!
Introduction
Without knowledge about namespaces and scope of a variable we cannot code coherently in Python. This topic is crucial, since it lays the foundation for variable behavior, which could cause problems if not understood properly.
Before we get into namespaces, a quick note on how variables work in python –
In statically typed languages like C, C++ and Java, variables have to be defined along with their datatypes. It is analogous to creating a box that can hold very specific values.
Python, on the other hand, is dynamically typed. This is analogous to the interpreter assigning a label to a variable. This label can be associated with any datatype.
This is important because while local variables can be easily identified (by their definitions) in statically typed languages, we need keywords like global and nonlocal to identify variables in Python.
What are Namespace and Scope?
A namespace is just a mapping from names to objects.
A scope is a textual region of a Python program where a namespace is directly accessible.
Basically, each python object has a scope, beyond which it does not exist (and hence cannot be accessed). The scope of a variable is essentially its lifetime during execution and is what defines the bounds of a namespace.
The following code snippet shows that accessing a variable outside its scope throws an error.
This code gives the output:
Since Python is an interpreted language, its code gets executed line by line. As a result of this, when we call foo(), it prints the value of variable a (10). But after control reaches the last line, the interpreter throws a NameError since a was defined inside the function (local variable).
Note: Scope of variable is slightly different in Python, when compared to other languages. For example, variables defined in compound statements in C do not last after the statement gets executed. Python, on the other hand, doesn’t limit variables to compound statements.
For example, the following C code will throw in an error during compilation
In Python we can define variables within for loops / with statements, and use them outside the compound statements without any errors
Types of Namespaces
The following Venn Diagram encompasses the various types of namespaces:
Global Namespace
The Global Namespace consists of the all variables defined at the main level of the program. If the python file is being used as a module (via the import) statement, then the global variables defined in that file are also imported and can be used accordingly.
Using global variables from imported files:
After running main.py, we get the output –
Make sure that both mathematics.py and main.py are in the same folder!
Local Namespace
A Local Namespace gets created when a local function is invoked. Objects declared in this namespace cannot be used outside the function.
above displays the behavior of a local variable.
Built-in
The built-in namespace contains predefined/built-in functions and objects. The scope of built-ins is the same as the lifetime of the entire program.
The following are some examples of built-ins:
These namespaces form the following scope hierarchy: Local > Global > Built-In
If there are 2 or more variables with the same name, the variable higher in the scope hierarchy will be used. These namespaces aren’t separate concepts. Instead, the local namespace is a subset of global, and the global namespace is a subset of built-in.
The most restricting namespace (local) is invoked during execution.