Are the python built-in methods available to reference in a package somewhere?
Let me explain. In my early(ier) days of python I made a django model similar to this
Use builtins, or __builtin__ if you're on Python 2.
def open():
pass
import __builtin__
print open
print __builtin__.open
This gives you:
<function open at 0x011E8670>
<built-in function open>
Python has a builtins module where "truly global" things—normally just the standard builtin functions and types—are stored. In Python 2, it was named __builtin__
, but worked mostly the same.
This module can be imported just like any other module—but it also magically supplies the builtin names for every other module (that doesn't hide them).
If you're wondering how that works, the builtins
docs say:
As an implementation detail, most modules have the name
__builtins__
made available as part of their globals. The value of__builtins__
is normally either this module or the value of this module’s__dict__
attribute. Since this is an implementation detail, it may not be used by alternate implementations of Python.
And exec says:
If the globals dictionary does not contain a value for the key
__builtins__
, a reference to the dictionary of the built-in modulebuiltins
is inserted under that key. That way you can control what builtins are available to the executed code by inserting your own__builtins__
dictionary into globals before passing it toexec()
.
So, at least in CPython, when you evaluate abs
, it's looked up in globals()['abs']
, not found there, and then looked up in globals()['__builtins__'].__dict__['abs']
.
And whenever Python (or at least CPython) creates a new module object, its code is executed against a globals
with an empty
__builtins__
, which means the default builtins
module value gets filled in, so that works. And this globals
is the one that gets copied for very function and class defined in the module (and anything you do explicitly with globals
without explicitly replacing __builtins__
), so it works inside functions and classes as well.