I'm trying out a coding challange right now. I cannot change the code before
del __builtins__.__dict__["__import__"]
but must use import afterwards. I need a way to restore the default __builtins__
. Its python 2.7.
I tryed __builtins__ = [x for x in (1).__class__.__base__.__subclasses__() if x.__name__ == 'catch_warnings'][0]()._module.__builtins__
but that doesn't work because the reference to builtins hasn't gone but the element from the dictionary of builtins are.
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__>
>>>
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__>
>>>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With