You would have to create a new function object from the old one:
newfunc = type(h)(h.__code__, cleaned_globals, h.__name__, h.__defaults__, h.__closure__)
Here, cleaned_globals
is a dictionary that is to be used as the global namespace for the newly created function object. All other arguments echo the original function's.
cleaned_globals
could be based on a copy of h.__globals__
, of course.
Demo:
>>> def h(i):
... f()
... return g(i)
...
>>> def g(i):
... return i + 1
...
>>> def f():
... print("Non-pure function")
...
>>> h(1)
Non-pure function
2
>>> cleaned_globals = {'g': g}
>>> newfunc = type(h)(h.__code__, cleaned_globals, h.__name__, h.__defaults__, h.__closure__)
>>> newfunc(1)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 2, in h
NameError: global name 'f' is not defined
>>> cleaned_globals['f'] = lambda: print('Injected function')
>>> newfunc(1)
Injected function
2