Namespace in Python

There are totally 4 types of namespace in python, that is LEGB. They are all independent from each other. However, there is priority among them. When compiler searches for a variable, it will search in the sequence of LEGB:

  • Locals: The namespace inside a function, which including local variables and formal parameters:
    1
    2
    3
    4
    def func1(x, y):
    a = 1
    print(locals())
    func1(1, 1)
    1
    2
    Output:
    {'x': 1, 'y': 1, 'a': 1}
  • Enclosing function: The namespace of outer function in nested function:
    1
    2
    3
    4
    5
    6
    7
    8
    9
    def func1(x, y):
    a = 1

    def func2(z, k):
    print(locals())

    func2(1, 1)

    func1(1, 1)
    1
    2
    output:
    {'z': 1, 'k': 1}
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    def func1(x, y):
    a = 1

    def func2(z, k):
    z += x
    k += y
    print(locals())

    func2(1, 1)

    func1(1, 1)
    1
    2
    output:
    {'z': 2, 'k': 2, 'x': 1, 'y': 1}
    This shows that the inner function can access to the outer function (only read) and add variables in enclosing function to its local namespace.
  • Globals: The namespace of current module, that is .py file, including variables, functions, classes and so on.
  • __builtins__: The namespace of built-in variables and built-in functions.

Variables in higher-priority namespaces will override variables with the same name in lower-priority namespaces.

Reference: