Single-dispatch generic function decorator. Transforms a function into a generic function, which can have different behaviours depending upon the type of its first argument. The decorated function acts as the default implementation, and additional implementations can be registered u
(func)
| 873 | return registry.get(match) |
| 874 | |
| 875 | def singledispatch(func): |
| 876 | """Single-dispatch generic function decorator. |
| 877 | |
| 878 | Transforms a function into a generic function, which can have different |
| 879 | behaviours depending upon the type of its first argument. The decorated |
| 880 | function acts as the default implementation, and additional |
| 881 | implementations can be registered using the register() attribute of the |
| 882 | generic function. |
| 883 | """ |
| 884 | # There are many programs that use functools without singledispatch, so we |
| 885 | # trade-off making singledispatch marginally slower for the benefit of |
| 886 | # making start-up of such applications slightly faster. |
| 887 | import weakref |
| 888 | |
| 889 | registry = {} |
| 890 | dispatch_cache = weakref.WeakKeyDictionary() |
| 891 | cache_token = None |
| 892 | |
| 893 | def dispatch(cls): |
| 894 | """generic_func.dispatch(cls) -> <function implementation> |
| 895 | |
| 896 | Runs the dispatch algorithm to return the best available implementation |
| 897 | for the given *cls* registered on *generic_func*. |
| 898 | |
| 899 | """ |
| 900 | nonlocal cache_token |
| 901 | if cache_token is not None: |
| 902 | current_token = get_cache_token() |
| 903 | if cache_token != current_token: |
| 904 | dispatch_cache.clear() |
| 905 | cache_token = current_token |
| 906 | try: |
| 907 | impl = dispatch_cache[cls] |
| 908 | except KeyError: |
| 909 | try: |
| 910 | impl = registry[cls] |
| 911 | except KeyError: |
| 912 | impl = _find_impl(cls, registry) |
| 913 | dispatch_cache[cls] = impl |
| 914 | return impl |
| 915 | |
| 916 | def _is_valid_dispatch_type(cls): |
| 917 | if isinstance(cls, type): |
| 918 | return True |
| 919 | return (isinstance(cls, UnionType) and |
| 920 | all(isinstance(arg, type) for arg in cls.__args__)) |
| 921 | |
| 922 | def register(cls, func=None): |
| 923 | """generic_func.register(cls, func) -> func |
| 924 | |
| 925 | Registers a new implementation for the given *cls* on a *generic_func*. |
| 926 | |
| 927 | """ |
| 928 | nonlocal cache_token |
| 929 | if _is_valid_dispatch_type(cls): |
| 930 | if func is None: |
| 931 | return lambda f: register(cls, f) |
| 932 | else: |
no test coverage detected