Are the python built-in methods available in an alternative namespace anywhere?

前端 未结 2 649
渐次进展
渐次进展 2020-12-20 19:48

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

相关标签:
2条回答
  • 2020-12-20 20:26

    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>
    
    0 讨论(0)
  • 2020-12-20 20:38

    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 module builtins 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 to exec().

    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.

    0 讨论(0)
提交回复
热议问题