Another related concept in Python are namespaces and scopes. The official Python documentation defines namespacing as mapping from names to object. While scope is defined as the textual region of a Python program where a namespace is directly accessible. A dictionary has a key and a value, demonstrating a key and value pair relationship. This relationship is an example of an ideal structure for the mapping of names and objects. Another example are Python modules. A module is a place where Python creates a module object. A module object contains the names of different attributes defined inside it. Therefore, it is a type or example of a namespace.
Namespaces and scopes can become confusing very quickly and so it is important to get as much practice of scopes as possible to ensure a standard of quality and efficiency when coding in Python. Now, the practice of trying to determine in which scope a certain variable belongs to is known as “Scope Resolution”. Scope Resolution follows what is commonly known as the “LEGB” rule where we have the four main type of scopes that are defined in Python. They are:
In simpler terms, a variable declared inside a function is local and the ones declared outside the scope of any function generally are global. Variables in Python are implicitly declared when you define them. That means unlike other programming languages, there is no special declaration made in Python which specifies its data type. What it also implies is that a given variable is local, not global when its declared unless it is stated otherwise.
Therefore, there are two keywords that can be used to change the scope of variable. We have the:
In conclusion, as a beginner in the journey of using Python , it is always a good idea and of best practice to integrate good practices in your code. Knowing how to use the concept of namespacing and scoping in your code shows not only your skill as a Developer but also how professional you are in your work space.
Introduction In the fast paced world of technology, learning a versatile and high-in-demand programming language…
Introduction User Authentication policy is a very crucial process for every application and organization. It…
Introduction In previous articles, we have learnt about Django, how it works and how we…
Introduction In this article, we shall learn how to build and implement a blog app.…
Introduction In this article, we shall use a database for the first time to build…
Introduction In this article, we will build a pages app that has a homepage and…