top of page
  • Writer's pictureDRL

Python Scope and Namespace

Updated: Apr 6


As in real life, the concept has been introduced in this programming language to make sure that all names in the program are unique and there is no ambiguity or conflict of any kind. It is a mapping from names to objects (like strings, lists, functions, etc). Most of them are implemented as a Python dictionary.

It is important to note that there is absolutely no relation between names in two or more different namespaces.

A global name of a module, set of attributes of an object, built-in names of python are all examples of namespace.


It is that region of a Python code from where an object is directly accessible. As the 'Scope of an object' defines from where it can be accessed, there is a restriction in from accessing any object from anywhere in the program. Although scopes are determined statically, they are used dynamically. Scope resolution of namespaces is done using LEGB rule. The scopes are listed below in terms of its hierarchy:

  • Local (L): Variables defined inside the current function. When the function ends, availability of that variable also ends.

  • Enclosed (E): Defined inside any and all enclosed functions or nested functions.

  • Global (G): It contains names at the top level of the module or beginning of the script. These names are available throughout the program or module or script.

  • Built-in (B): Contains reserved names built-in for Python language.

In order to modify global variable inside local scope, we need the keyword - global.
In order to modify non-local variable inside the local scope, we need the keyword - nonlocal

Common Errors

In case the scope of the object is not correct while accessing it, following error(s) might be encountered with the Python compilation.

  • NameError: This arises when we try to access a name in a scope where that name has not been defined. As in the following snippet, x is defined inside the 'local' function only and can't be accessed from outside. When the above code gets executed, line 4 throws the value of 'x' but line 5 gives an error - 'NameError: name 'x' is not defined'.

  • UnboundLocalError: This is raised when a local variable is referenced before it has been assigned. In order to rectify this error, one simple modification could be to make y as global inside the 'fun' using global keyword. When the above code gets executed, line 5 calls the function - 'fun'. As the variable is referenced before assignment, throws error - 'UnboundLocalError: local variable 'y' referenced before assignment'.

24 views0 comments

Recent Posts

See All
bottom of page