Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get __import__ back after removing it with del __builtins__.__dict__["__import__"]

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.

like image 514
roboalex2 Avatar asked Sep 10 '25 14:09

roboalex2


1 Answers

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__>
>>>
like image 146
blhsing Avatar answered Sep 12 '25 03:09

blhsing