HomeAbout

What is Python Namespaces

Namespaces are like containers that hold names (identifiers like variables, functions, classes, etc.) and map them to their corresponding objects.

Namespace prevents name collisions by isolating variable/function names used in different parts of a program.

x = 10 # Global namespace def outer(): y = 20 # Enclosing namespace def inner(): z = 30 # Local namespace print(x, y, z) inner() outer()

Built-in namespaces are called when Python interpreter starts.

Global namespaces are called when module or script is run.

Local namespaces are called when a function is called.

  • Namespace is destroyed when function returns.

Enclosing namespaces are nested functions.

  • inner function has access to the outer function's variables.

LEGB rule

Python looks up names in following order:

  • Local
  • Enclosing
  • Global
  • Built-in
AboutContact