我想用 python 编写一个上下文管理器,暂时全局禁用某个函数。一般情况下可以做这样的事情吗?以下是所需行为的示例:
#in module x
def disable_me(): print "do stuff"
#in module y
import x
def run_me():
print "run_me"
x.disable_me()
#in module z
import x
import y
with disable_function(x.disable_me):
y.run_me()
#desired output: run_me
我知道,原则上我可以暂时分配lambda *args, **kwargs: None
至x.disable_me
但我不清楚上下文管理器是否有足够的信息来实际执行此操作。
最佳答案
这实际上相当容易做到,只要您不介意传递包含对象和变量名称,而不是变量本身(这不应该是问题)。
from contextlib import contextmanager
class X:
def disable_me():
print("do stuff")
def run_me(x):
print("run_me")
x.disable_me()
@contextmanager
def disable_function(obj, name):
temp = getattr(obj, name)
setattr(obj, name, lambda: None)
yield
setattr(obj, name, temp)
x = X()
with disable_function(x, "disable_me"):
run_me(x)
这适用于模块和对象,但在这样的一个文件中显示更容易。
关于python - 可以用 Python 中的上下文管理器全局替换函数吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10388411/