古い関数オブジェクトから新しい関数オブジェクトを作成する必要があります。
newfunc = type(h)(h.__code__, cleaned_globals, h.__name__, h.__defaults__, h.__closure__)
ここでcleaned_globals
は、新しく作成された関数オブジェクトのグローバル名前空間として使用される辞書です。他のすべての引数は、元の関数のものをエコーします。
cleaned_globals
h.__globals__
もちろん、のコピーに基づいている可能性があります。
デモ:
>>> 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