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'