Artificial Intelligence Design Innovation Machine Learning Technology

Namespacing and Scoping in Python

Pinterest LinkedIn Tumblr

Introduction

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.

Why should developers understand the relationship between namespaces and scopes?

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:

  • Local: This is when the first and foremost search for a variable is in the local scope.
  • Enclosed: This is defined inside an enclosing or nested function.
  • Global: This is defined at the uppermost level or simply outside functions.
  • Built-in: This refers to the keywords present in the built-in module.
ALSO READ  Free Wifi: Is It Safe?

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:

  • Global Keyword: The global keyword helps us access the global variable from within the function.
  • Non-local Keyword: This is a special type of scope defined in Python. This keyword is used within the nested functions only in the condition that it has been defined earlier in the enclosed functions.

Conclusion

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.