Skip to content

Commit a831a8c

Browse files
committed
gh-162703: Fix singledispatch cache invalidation for ABCs registered in a union
1 parent 5dbe2ac commit a831a8c

3 files changed

Lines changed: 32 additions & 4 deletions

File tree

‎Lib/functools.py‎

Lines changed: 7 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -979,11 +979,14 @@ def register(cls, func=None):
979979
)
980980

981981
if isinstance(cls, UnionType):
982-
for arg in cls.__args__:
983-
registry[arg] = func
982+
classes = cls.__args__
984983
else:
985-
registry[cls] = func
986-
if cache_token is None and hasattr(cls, '__abstractmethods__'):
984+
classes = (cls,)
985+
for arg in classes:
986+
registry[arg] = func
987+
if cache_token is None and any(
988+
hasattr(arg, '__abstractmethods__') for arg in classes
989+
):
987990
cache_token = get_cache_token()
988991
dispatch_cache.clear()
989992
return func

‎Lib/test/test_functools.py‎

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3496,6 +3496,28 @@ def _(arg: int | None):
34963496
self.assertEqual(types_union(1), "types.UnionType")
34973497
self.assertEqual(types_union(None), "types.UnionType")
34983498

3499+
def test_union_abc_cache_invalidation(self):
3500+
# gh-162703: registering an ABC as part of a union must still
3501+
# invalidate the dispatch cache when the ABC gains a virtual subclass.
3502+
class A(abc.ABC):
3503+
pass
3504+
3505+
class B:
3506+
pass
3507+
3508+
@functools.singledispatch
3509+
def f(arg):
3510+
return "default"
3511+
3512+
@f.register
3513+
def _(arg: A | bytes):
3514+
return "A | bytes"
3515+
3516+
b = B()
3517+
self.assertEqual(f(b), "default")
3518+
A.register(B)
3519+
self.assertEqual(f(b), "A | bytes")
3520+
34993521
def test_register_genericalias(self):
35003522
@functools.singledispatch
35013523
def f(arg):
Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
Fix :func:`functools.singledispatch` not invalidating its dispatch cache
2+
after :meth:`abc.ABCMeta.register` when the abstract base class was
3+
registered as part of a union type.

0 commit comments

Comments
 (0)