有没有办法“注销”泛型的已注册函数?在
例如:
from functools import singledispatch
@singledispatch
def foo(x):
return 'default function'
foo.register(int, lambda x: 'function for int')
# later I would like to revert this.
foo.unregister(int) # does not exist - this is the functionality I am after
singledispatch
只能追加;您不能真正注销任何内容。在但与Python的所有东西一样,实现可能会被迫注销。以下函数将向单个分派函数添加
unregister()
方法:这涉及到
singledispatch.register()
函数的闭包,以访问实际的registry
字典,这样我们就可以删除已注册的现有类。我还清除了dispatch_cache
弱引用字典,以防止它介入。在您可以将其用作装饰:
^{pr2}$演示:
相关问题 更多 >
编程相关推荐