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 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…
When you say you want to use Django, it means you want to build a…
Introduction Django is a high level Python framework that encourages rapid development and clean, pragmatic…
Django Setup To work with Django, we have to install Django first. Now when you…
Why choose Django when you have other frameworks for Python? Django, Django, Django. When it…