Skip to content

Commit

Permalink
simplify, extend docs
Browse files Browse the repository at this point in the history
  • Loading branch information
JelleZijlstra committed Sep 28, 2024
1 parent f500f5f commit 5f9e599
Show file tree
Hide file tree
Showing 2 changed files with 6 additions and 7 deletions.
4 changes: 3 additions & 1 deletion Doc/library/typing.rst
Original file line number Diff line number Diff line change
Expand Up @@ -1125,7 +1125,9 @@ These can be used as types in annotations. They all support subscription using
:class:`types.UnionType` is now an alias for :class:`Union`, and both
``Union[int, str]`` and ``int | str`` create instances of the same class.
To check whether an object is a ``Union`` at runtime, use
``isinstance(obj, Union)``.
``isinstance(obj, Union)``. For compatibility with earlier versions of
Python, use
``get_origin(obj) is typing.Union or get_origin(obj) is types.UnionType``.

.. data:: Optional

Expand Down
9 changes: 3 additions & 6 deletions Lib/functools.py
Original file line number Diff line number Diff line change
Expand Up @@ -930,13 +930,10 @@ def dispatch(cls):
dispatch_cache[cls] = impl
return impl

def _is_union_type(cls):
return isinstance(cls, UnionType)

def _is_valid_dispatch_type(cls):
if isinstance(cls, type):
return True
return (_is_union_type(cls) and
return (isinstance(cls, UnionType) and
all(isinstance(arg, type) for arg in cls.__args__))

def register(cls, func=None):
Expand Down Expand Up @@ -969,7 +966,7 @@ def register(cls, func=None):
from annotationlib import Format, ForwardRef
argname, cls = next(iter(get_type_hints(func, format=Format.FORWARDREF).items()))
if not _is_valid_dispatch_type(cls):
if _is_union_type(cls):
if isinstance(cls, UnionType):
raise TypeError(
f"Invalid annotation for {argname!r}. "
f"{cls!r} not all arguments are classes."
Expand All @@ -985,7 +982,7 @@ def register(cls, func=None):
f"{cls!r} is not a class."
)

if _is_union_type(cls):
if isinstance(cls, UnionType):
for arg in cls.__args__:
registry[arg] = func
else:
Expand Down

0 comments on commit 5f9e599

Please sign in to comment.