generic_func.register(cls, func) -> func Registers a new implementation for the given *cls* on a *generic_func*.
(cls, func=None)
| 850 | all(isinstance(arg, type) for arg in get_args(cls))) |
| 851 | |
| 852 | def register(cls, func=None): |
| 853 | """generic_func.register(cls, func) -> func |
| 854 | |
| 855 | Registers a new implementation for the given *cls* on a *generic_func*. |
| 856 | |
| 857 | """ |
| 858 | nonlocal cache_token |
| 859 | if _is_valid_dispatch_type(cls): |
| 860 | if func is None: |
| 861 | return lambda f: register(cls, f) |
| 862 | else: |
| 863 | if func is not None: |
| 864 | raise TypeError( |
| 865 | f"Invalid first argument to `register()`. " |
| 866 | f"{cls!r} is not a class or union type." |
| 867 | ) |
| 868 | ann = getattr(cls, '__annotations__', {}) |
| 869 | if not ann: |
| 870 | raise TypeError( |
| 871 | f"Invalid first argument to `register()`: {cls!r}. " |
| 872 | f"Use either `@register(some_class)` or plain `@register` " |
| 873 | f"on an annotated function." |
| 874 | ) |
| 875 | func = cls |
| 876 | |
| 877 | # only import typing if annotation parsing is necessary |
| 878 | from typing import get_type_hints |
| 879 | argname, cls = next(iter(get_type_hints(func).items())) |
| 880 | if not _is_valid_dispatch_type(cls): |
| 881 | if _is_union_type(cls): |
| 882 | raise TypeError( |
| 883 | f"Invalid annotation for {argname!r}. " |
| 884 | f"{cls!r} not all arguments are classes." |
| 885 | ) |
| 886 | else: |
| 887 | raise TypeError( |
| 888 | f"Invalid annotation for {argname!r}. " |
| 889 | f"{cls!r} is not a class." |
| 890 | ) |
| 891 | |
| 892 | if _is_union_type(cls): |
| 893 | from typing import get_args |
| 894 | |
| 895 | for arg in get_args(cls): |
| 896 | registry[arg] = func |
| 897 | else: |
| 898 | registry[cls] = func |
| 899 | if cache_token is None and hasattr(cls, '__abstractmethods__'): |
| 900 | cache_token = get_cache_token() |
| 901 | dispatch_cache.clear() |
| 902 | return func |
| 903 | |
| 904 | def wrapper(*args, **kw): |
| 905 | if not args: |
nothing calls this directly
no test coverage detected