Is there way to "unregister" a registered function for a generic ?
For example:
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
singledispatchis meant to be append only; you cannot really unregister anything.But as with all things Python, the implementation can be forced to unregister. The following function will add a
unregister()method to a singledispatch function:This reaches into the closure of the
singledispatch.register()function to access the actualregistrydictionary so we can remove an existing class that was registered. I also clear thedispatch_cacheweak reference dictionary to prevent it from stepping in.You can use this as a decorator:
Demo: