Python namespaces & LEGB rule in Python

What are Python namespaces? What is the LEGB rule in Python?

A namespace in Python ensures that object names in a program are unique and can be used without any conflict. Python implements these namespaces as dictionaries with 'name as key' mapped to a corresponding 'object as value'. This allows for multiple namespaces to use the same name and map it to a separate object. A few examples of namespaces are as follows:

  • Local Namespace includes local names inside a function. the namespace is temporarily created for a function call and gets cleared when the function returns.
  • Global Namespace includes names from various imported packages/ modules that are being used in the current project. This namespace is created when the package is imported in the script and lasts until the execution of the script.
  • Built-in Namespace includes built-in functions of core Python and built-in names for various types of exceptions.

The lifecycle of a namespace depends upon the scope of objects they are mapped to. If the scope of an object ends, the lifecycle of that namespace comes to an end. Hence, it isn't possible to access inner namespace objects from an outer namespace.

LEGB stands for Local, Enclosing, Global, Built-in. These are the possible scopes of a variable in Python. We also use these words to describe namespaces, which store variable names and values and are how Python determines scope.

The order Local, Enclosing, Global, Built-in is the order of precedence for scope resolution. That means Python searches for the value of a name in each of these namespaces in turn.

Below is the diagram for LEGB ref.:



Comments