Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to restore a builtin function after deleting it? [duplicate]

After deleting a builtin function like this, I want to restore it without restarting the interpreter.

>>> import builtins
>>> del builtins.eval
>>> builtins.eval = None

I tried reloading the builtin module using importlib, that didn't restore eval.

>>> import importlib
>>> importlib.reload(builtins)
<module 'builtins' (built-in)>
>>> eval("5 + 5")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'NoneType' object is not callable

I also tried to assign a __builtins__ variable from another module. That didn't work as well.

>>> import os
>>> __builtins__ = os.__builtins__
>>> eval()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'NoneType' object is not callable

Is there a way to restore a builtin function after deleting it?

like image 576
Ahmed Tounsi Avatar asked Oct 15 '25 16:10

Ahmed Tounsi


2 Answers

I think the usage pattern of builtins is different from what you suggest. What you typically do is that you re-bind a built-in name for your purpose and then use builtins to restore the functionality:

eval = None

eval('5 + 5')
# TypeError: 'NoneType' object is not callable


import builtins


eval = builtins.eval
eval('5 + 5')
# 10

or (as commented by @ShadowRanger), even more simply in this specific case:


eval = None

eval('5 + 5')
# TypeError: 'NoneType' object is not callable

del eval

eval('5 + 5')
# 10
like image 146
norok2 Avatar answered Oct 18 '25 05:10

norok2


After posting the question I figured out a way to restore it using the BuiltinImporter.

>>> import builtins
>>> del builtins.eval
>>> builtins.eval = None
>>> eval()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'NoneType' object is not callable
>>> import importlib
>>> bi = importlib.machinery.BuiltinImporter
>>> bi.load_module("builtins")
<module 'builtins' (built-in)>
>>> import sys
>>> __builtins__ = bi.load_module.__globals__['module_from_spec'](sys.modules['builtins'].__spec__)
>>> eval("5 + 5")
10
like image 34
Ahmed Tounsi Avatar answered Oct 18 '25 07:10

Ahmed Tounsi