是否有办法取消注册"通用的注册函数?
例如:
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
答案 0 :(得分:4)
singledispatch
只是仅追加;你不能真正注销任何东西。
但是就像Python一样,实现可以被强制取消注册。以下函数将unregister()
方法添加到singledispatch函数:
def add_unregister(func):
# build a dictionary mapping names to closure cells
closure = dict(zip(func.register.__code__.co_freevars,
func.register.__closure__))
registry = closure['registry'].cell_contents
dispatch_cache = closure['dispatch_cache'].cell_contents
def unregister(cls):
del registry[cls]
dispatch_cache.clear()
func.unregister = unregister
return func
这将进入singledispatch.register()
函数的闭包,以访问实际的registry
字典,这样我们就可以删除已注册的现有类。我还清除了dispatch_cache
弱引用字典,以防止它进入。
您可以将其用作装饰者:
@add_unregister
@singledispatch
def foo(x):
return 'default function'
演示:
>>> @add_unregister
... @singledispatch
... def foo(x):
... return 'default function'
...
>>> foo.register(int, lambda x: 'function for int')
<function <lambda> at 0x10bed6400>
>>> foo.registry
mappingproxy({<class 'object'>: <function foo at 0x10bed6510>, <class 'int'>: <function <lambda> at 0x10bed6400>})
>>> foo(1)
'function for int'
>>> foo.unregister(int)
>>> foo.registry
mappingproxy({<class 'object'>: <function foo at 0x10bed6510>})
>>> foo(1)
'default function'