Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 7 additions & 4 deletions Lib/functools.py
Original file line number Diff line number Diff line change
Expand Up @@ -979,11 +979,14 @@ def register(cls, func=None):
)

if isinstance(cls, UnionType):
for arg in cls.__args__:
registry[arg] = func
classes = cls.__args__
else:
registry[cls] = func
if cache_token is None and hasattr(cls, '__abstractmethods__'):
classes = (cls,)
for arg in classes:
registry[arg] = func
if cache_token is None and any(
hasattr(arg, '__abstractmethods__') for arg in classes
):
cache_token = get_cache_token()
dispatch_cache.clear()
return func
Expand Down
22 changes: 22 additions & 0 deletions Lib/test/test_functools.py
Original file line number Diff line number Diff line change
Expand Up @@ -3496,6 +3496,28 @@ def _(arg: int | None):
self.assertEqual(types_union(1), "types.UnionType")
self.assertEqual(types_union(None), "types.UnionType")

def test_union_abc_cache_invalidation(self):
# gh-162703: registering an ABC as part of a union must still
# invalidate the dispatch cache when the ABC gains a virtual subclass.
class A(abc.ABC):
pass

class B:
pass

@functools.singledispatch
def f(arg):
return "default"

@f.register
def _(arg: A | bytes):
return "A | bytes"

b = B()
self.assertEqual(f(b), "default")
A.register(B)
self.assertEqual(f(b), "A | bytes")

def test_register_genericalias(self):
@functools.singledispatch
def f(arg):
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
Fix :func:`functools.singledispatch` not invalidating its dispatch cache
after :meth:`abc.ABCMeta.register` when the abstract base class was
registered as part of a union type.
Loading