4

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.

roboalex2
  • 80
  • 5
  • 3
    **Patient**: Doctor, it hurts when I do this. **Doctor**: Don't do that. – Peter Wood Apr 11 '19 at 21:24
  • Possible duplicate of [can you recover from reassigning \_\_builtins\_\_ in python?](https://stackoverflow.com/questions/13307110/can-you-recover-from-reassigning-builtins-in-python) – Peter Wood Apr 11 '19 at 21:26
  • I'm curious. What's the point of this "coding challenge"? – CryptoFool Apr 11 '19 at 21:34
  • @PeterWood won't work, since `__builtins__` is a reference to the same namespace in every module. – juanpa.arrivillaga Apr 11 '19 at 21:35
  • @Steve The actual challange is simpler but I would like to get extra points. https://hacking-lab.com/cases/5138-escape-from-python-city/5138-escape-from-python-city-wargame.html?event=199&case=990 – roboalex2 Apr 11 '19 at 21:47
  • @roboalex2 Unfortunately, that link requires a login/password to view the challenge. – AJNeufeld Apr 11 '19 at 22:24

1 Answers1

6

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__>
>>>
blhsing
  • 91,368
  • 6
  • 71
  • 106
  • 1
    I would have thought ugly problems would require ugly solutions, but this seems beautiful in a way. – Nick Vitha Apr 11 '19 at 22:07
  • @blhsing It's a real elegenate solution. But unfortunately not for me. I forgot to mention that it is Python 2.7. I'm sorry. – roboalex2 Apr 11 '19 at 22:20