diff --git a/Lib/functools.py b/Lib/functools.py index a6cc155b65a4b0..5d1d9f165e2544 100644 --- a/Lib/functools.py +++ b/Lib/functools.py @@ -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 diff --git a/Lib/test/test_functools.py b/Lib/test/test_functools.py index 7727cba4f55f4f..a8b08e0451a62b 100644 --- a/Lib/test/test_functools.py +++ b/Lib/test/test_functools.py @@ -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): diff --git a/Misc/NEWS.d/next/Library/2026-11-27-04-00-47.gh-issue-162703.Ofxyyv.rst b/Misc/NEWS.d/next/Library/2026-11-27-04-00-47.gh-issue-162703.Ofxyyv.rst new file mode 100644 index 00000000000000..ea36c4c1ba1a0a --- /dev/null +++ b/Misc/NEWS.d/next/Library/2026-11-27-04-00-47.gh-issue-162703.Ofxyyv.rst @@ -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.