Python variable scope LEGB (above) - Local, Global, Builtin

Keywords: Python ascii

The rule for Python variable scope is LEGB

Explanation of the meaning of LEGB:
L - Local(function); namespaces within functions
E - Enclosing function locals; namespaces for externally nested functions (such as closure)
G - Global(module); the namespace of the module (file) where the function definition is located
B - Builtin(Python); namespace for Python built-in modules

 

I. Builtin

In fact, this part is mainly Python's built-in namespace, mainly built-in functions, exception classes and so on. You can view it by dir (u builtins_u)

>>> dir(__builtins__)
 ['ArithmeticError', 'AssertionError', 'AttributeError', 'BaseException', 'BlockingIOError', 'BrokenPipeError', 
'BufferError', 'BytesWarning', 'ChildProcessError', 'ConnectionAbortedError', 'ConnectionError',
'ConnectionRefusedError', 'ConnectionResetError', 'DeprecationWarning', 'EOFError', 'Ellipsis', 'EnvironmentError',
'Exception', 'False', 'FileExistsError', 'FileNotFoundError', 'FloatingPointError', 'FutureWarning',
'GeneratorExit', 'IOError', 'ImportError', 'ImportWarning', 'IndentationError', 'IndexError', 'InterruptedError',
'IsADirectoryError', 'KeyError', 'KeyboardInterrupt', 'LookupError', 'MemoryError', 'NameError', 'None',
'NotADirectoryError', 'NotImplemented', 'NotImplementedError', 'OSError', 'OverflowError',
'PendingDeprecationWarning', 'PermissionError', 'ProcessLookupError', 'ReferenceError', 'ResourceWarning',
'RuntimeError', 'RuntimeWarning', 'StopIteration', 'SyntaxError', 'SyntaxWarning', 'SystemError', 'SystemExit',
'TabError', 'TimeoutError', 'True', 'TypeError', 'UnboundLocalError', 'UnicodeDecodeError', 'UnicodeEncodeError',
'UnicodeError', 'UnicodeTranslateError', 'UnicodeWarning', 'UserWarning', 'ValueError', 'Warning', 'WindowsError',
'ZeroDivisionError', '_', '__build_class__', '__debug__', '__doc__', '__import__', '__loader__', '__name__',
'__package__', '__spec__', 'abs', 'all', 'any', 'ascii', 'bin', 'bool', 'bytearray', 'bytes', 'callable', 'chr',
'classmethod', 'compile', 'complex', 'copyright', 'credits', 'delattr', 'dict', 'dir', 'divmod', 'enumerate',
'eval', 'exec', 'exit', 'filter', 'float', 'format', 'frozenset', 'getattr', 'globals', 'hasattr', 'hash', 'help',
'hex', 'id', 'input', 'int', 'isinstance', 'issubclass', 'iter', 'len', 'license', 'list', 'locals', 'map', 'max',
'memoryview', 'min', 'next', 'object', 'oct', 'open', 'ord', 'pow', 'print', 'property', 'quit', 'range', 'repr',
'reversed', 'round', 'set', 'setattr', 'slice', 'sorted', 'staticmethod', 'str', 'sum', 'super', 'tuple', 'type',
'vars', 'zip']

This part of the general situation should not be modified.

1) When a real modification/deletion or addition is made, it is necessary to specify u builtins_uuuuuuuuuuuuu

2) Additionally, you can add names of the same name locally, because Locals and Global take precedence over builtin, and that name takes precedence over Builtin.

For example, yvivid defines str as 123 under Global, and when str is invoked, str under Global is invoked first (that is, 123).

>>> str = 123
>>> print(str)
123
>>> dir()
['__builtins__', '__doc__', '__loader__', '__name__', '__package__', '__spec__', 'str']

 

Two, Global

This part is the Module layer, if the interaction interface, is the scene of the current interaction interface.

You can view all variables of globals through globals().

>>> globals()
{'__doc__': None, '__spec__': None, '__loader__': <class '_frozen_importlib.BuiltinImporter'>, '__builtins__': <module 'builtins' (built-in)>, '__package__': None, '__name__': '__main__'}

When calling a module, you need to specify a path, such as sys.int_info in the following example

>>> import sys
>>> sys.int_info
sys.int_info(bits_per_digit=30, sizeof_digit=4)

 

Three, Local

This part generally refers to the variable space within the function, through locals() you can see all variables of Local.

1) Using locals() directly in the module layer or in the interaction interface, the return result is exactly the same as that of globals. Because, without a separate local scenario, global and local are the same namespace.

>>> globals()
{'__doc__': None, '__spec__': None, '__loader__': <class '_frozen_importlib.BuiltinImporter'>, '__builtins__': <module 'builtins' (built-in)>, '__package__': None, '__name__': '__main__'}
>>> locals()
{'__doc__': None, '__spec__': None, '__loader__': <class '_frozen_importlib.BuiltinImporter'>, '__builtins__': <module 'builtins' (built-in)>, '__package__': None, '__name__': '__main__'}

2) In the function, look at locals. The following example:

>>> x = 10
>>> def func(y=3):
    temp = 7
    print('Locals =', locals())
    print('Globals =', globals())
    return y+temp
>>> t = func()
Locals = {'temp': 7, 'y': 3}
Globals = {'__loader__': <class '_frozen_importlib.BuiltinImporter'>, '__package__': None, 'x': 10, '__spec__': None, '__name__': '__main__', 
'__builtins__': <module 'builtins' (built-in)>, 'func': <function func at 0x0000000003E5B378>, '__doc__': None}

You can see that the namespaces of locals() and globals() are quite different.

Other points for attention:

1) for loops are not local: but scoped locally when the list is derived. yvivid: The point is to pay attention to this, which will be mentioned later in the Enclose section.

>>> for i in range(4):
        print(locals())
.... Repeated the namespace associated with globals() four times
>>> print(i)
3 # I is still better than recorded
>>> [ locals() for i in range(4)]
[{'.0': <range_iterator object at 0x00000000036AA7F0>, 'i': 3},
{'.0': <range_iterator object at 0x00000000036AA7F0>, 'i': 3},
{'.0': <range_iterator object at 0x00000000036AA7F0>, 'i': 3},
{'.0': <range_iterator object at 0x00000000036AA7F0>, 'i': 3}]
>>> print(i)
Traceback (most recent call last):
  File "<pyshell#1>", line 1, in <module>
    print(i)
NameError: name 'i' is not defined

2) In functions, using Global is a bad habit. This is not much to say, you can basically understand.

 

Unfinished, the next section explains the scope of Enclosing function locals; the namespace of externally nested functions, such as closure.

-------

A. The code is based on Python 3.4 environment.

B. Reference book Python Learning Manual (4th Edition)

[Original document, quote please declare the source, yvivid]

Posted by Bijan on Thu, 13 Dec 2018 14:06:14 -0800