Namespace, Scope , LEGB rule and global and non-local variable in python

Namespace:

Keerti Prajapati
Analytics Vidhya

--

In Python, everything is an object and we give a name to the object so that we can access it later on.

You can think of namespace as a dictionary of key-value pairs where the key is the variable name and the value is the object associated with it.

Scope

Scope of variable defines the hierarchy in which we search for a variable.

Scope of variable in python is a place or part of code where it is accessible or visible.

LEGB:

The LEGB rule is used to decide the order in which the namespaces are to be searched for scope resolution.

Scope of variable can be local(L),enclosed(E), global(G),built-in(B).

Let’s understand whole concept with the help of example:

In above example, variable a,b is not defined inside any function hence they are global variables. They can be accessed anywhere in program.

Now look at the local_function() , here we again have variable a, but it can only be accessed within function ,hence it is called as local variable.

When we call local_function() output will be,

--

--