the global keyword:

eryk sun eryksun at gmail.com
Thu Jun 23 22:19:57 EDT 2016


On Fri, Jun 24, 2016 at 1:00 AM, Steven D'Aprano <steve at pearwood.info> wrote:
> To be precise, for the builtins module specifically, you can *read* the
> value of the variable using just x, but you cannot *assign* to it unless
> you use the fully-qualified name builtins.x.

FWIW, you can execute code in any dict:

    >>> import builtins
    >>> exec(r'''
    ... foo = 'bar'
    ... ''', vars(builtins))
    >>> builtins.foo
    'bar'

The frame for an unoptimized CPython code object (used for modules and
the class statement) uses f_builtins, f_globals, and f_locals dicts
(or possibly a mapping in the case of f_locals) respectively for its
builtin, global, and local scopes. The frame for an optimized code
object uses a fast locals array instead of f_locals, in which case the
locals() function stores a snapshot of the locals to the f_locals
dict. A frame may also have a freevars array, which has cell objects
for closures (i.e. the nonlocal scope). For optimized code (i.e. a
function, but not a class body), locals() also includes a snapshot of
nonlocals, even though this doesn't make literal sense.

The above example executes code with all 3 scopes set to the same
dict. For example:

    >>> exec(r'''
    ... import sys
    ... f = sys._getframe()
    ... print(f.f_builtins is f.f_globals is f.f_locals)
    ... ''', vars(builtins))
    True

The CPython VM doesn't have an operation to store to the builtin
scope, since the language doesn't have a statement such as "builtin"
to declare a variable in this scope. The builtin scope is used as a
fallback for operations such as LOAD_NAME and LOAD_GLOBAL -- for
loading constants such as built-in functions, exceptions, __debug__,
and also the "_" attribute that gets updated by sys.displayhook.



More information about the Python-list mailing list