使用del __builtins __.__ dict __ [“ __ import__”]删除后如何找回__import__

rob*_*ex2 3 python python-2.7

我正在尝试编码挑战。我之前无法更改代码, del __builtins__.__dict__["__import__"]但之后必须使用导入。我需要一种恢复默认值的方法__builtins__。其python 2.7。

我试过了,__builtins__ = [x for x in (1).__class__.__base__.__subclasses__() if x.__name__ == 'catch_warnings'][0]()._module.__builtins__但是那行不通,因为对内置函数的引用还没有,但是内置函数字典中的元素已经存在。

blh*_*ing 5

In Python 2, you can use the reload function to get a fresh copy of the __builtins__ module:

>>> del __builtins__.__dict__['__import__']
>>> reload(__builtins__)
<module '__builtin__' (built-in)>
>>> __import__
<built-in function __import__>
>>>
Run Code Online (Sandbox Code Playgroud)

In Python 3, the reload function has been moved to the imp module (and in Python 3.4, importlib) so importing imp or importlib isn't option without __import__. Instead, you can use __loader__.load_module to load the sys module and delete the cached but ruined copy of the builtins module from the sys.modules dict, so that you can load a new copy of the builtins module with __loader__.load_module:

>>> del __builtins__.__dict__['__import__']
>>> del __loader__.load_module('sys').modules['builtins']
>>> __builtins__ = __loader__.load_module('builtins')
>>> __import__
<built-in function __import__>
>>>
Run Code Online (Sandbox Code Playgroud)