Scope Resolution in Python- LEGB Rule:

Namespaces: It is a container where names are mapped to objects. These are helpful for avoiding confusion when the same name exists in different namespaces. They are created by functions, modules, classes, etc. Here, we will learn about scope in python for data science purposes.

Scope: It defines the hierarchical order in which we have to search the namespaces for obtaining the mapping o the name-to-object (variables). Variables exist in this context, and from this, they are reference. It also defines the lifetime and accessibility of a variable. Below is an example.

Scope Resolution in Python- LEGB Rule for Data Science - PST Analytics

Scope resolution via LEGB rule:

We use the LEGB rule in Python for deciding the order in which the namespaces are search for scope resolution.

Below we have listed the scopes in terms of their hierarchy (narrowest t broadest):

  • Local (L) – We can define it inside the function class.
  • Enclosed (E) – We can define it inside the enclosing function (Nested function).
  • Global (G) – We can define it at the uppermost level.
  • Built-in (B) – These are the reserve name in the built-in modules of Python.

Scope Resolution in Python- LEGB Rule for Data Science - PST Analytics

Local Scope:

It refers to the variables which are define in the current function. A function will always look for the variable name in the local scope. In case there is nothing in the local scope other scopes are search.

When we run the above program, the inner function will get execute, and the function will print the value of local variable pi as it is available in the local scope.

Local and Global scopes:

In case no variable is found in the local scope, it will check for the next higher scope, i.e., global scope.

Local, enclosed, and global scopes:

In case of an enclose function, we need to define an outer function that encloses the inner function. We will comment out the local pi variable of inner function, and it will be referr to the variable pi by using the non-local keyword.

Scope Resolution in Python- LEGB Rule for Data Science - PST Analytics

When the program output() is execute, the inner() and the print functions will be executed, and then the value enclose in the pi variable is printed.

Local, enclosed, global, and built-in scopes:

We will do the final check by importing pi from the math module, and then we will comment global, enclose, and local pi variables.

As pi is not defined in any of the scope it will look up in the built-in scope, i.e., it will import from math module. Also, to learn more about it in python for data science, you can check this and this as well.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.