This issue tracker has been migrated to GitHub, and is currently read-only.
For more information, see the GitHub FAQs in the Python's Developer Guide.

Author eryksun
Recipients docs@python, eryksun, mdk, xcombelle
Date 2016-12-01.03:30:34
SpamBayes Score -1.0
Marked as misclassified Yes
Message-id <1480563034.74.0.478986569543.issue26363@psf.upfronthosting.co.za>
In-reply-to
Content
As shown above, exec and eval default to calling PyEval_GetBuiltins when the globals dict doesn't define '__builtins__'. PyEval_GetBuiltins uses the current frame's f_builtins. If there isn't a current frame, it defaults to the interpreter's builtins, which should be the dict of the builtins module. 

If exec and eval didn't do this, the default behavior would be to create a minimal f_builtins dict for the new frame. This dict only contains a reference to None, and it doesn't get set as '__builtins__' in globals. For example:

    from inspect import currentframe
    from ctypes import pythonapi, py_object
    g = py_object({'currentframe': currentframe})
    code = py_object(compile('currentframe()', '', 'eval'))
    frame = pythonapi.PyEval_EvalCode(code, g, g)

    >>> frame.f_builtins
    {'None': None}
    >>> frame.f_globals
    {'currentframe': <function currentframe at 0x7f2fa1d6c2f0>}

This minimalist default isn't useful in general. exec and eval are saving people from the tedium of having to manually define a useful __builtins__ when passing a new globals. The frame object uses this __builtins__ to initialize its f_builtins. Also, it knows to look for __builtins__ as a module, as used by __main__:

    g = py_object({'currentframe': currentframe, '__builtins__': __builtins__})
    frame = pythonapi.PyEval_EvalCode(code, g, g)

    >>> frame.f_builtins is vars(__builtins__)
    True
History
Date User Action Args
2016-12-01 03:30:34eryksunsetrecipients: + eryksun, docs@python, xcombelle, mdk
2016-12-01 03:30:34eryksunsetmessageid: <1480563034.74.0.478986569543.issue26363@psf.upfronthosting.co.za>
2016-12-01 03:30:34eryksunlinkissue26363 messages
2016-12-01 03:30:34eryksuncreate