Skip to content

singledispatch keeps a stale handler after ABC.register() when the ABC was registered in a union #162703

Backlog

Description

@limadog9

Bug report

When a singledispatch handler is registered for Message | bytes, registering a new virtual subclass of Message does not invalidate a previously cached dispatch decision for that class.

from abc import ABC
from functools import singledispatch

class Message(ABC):
    pass

class Event:
    pass

@singledispatch
def encode(value):
    return "default"

@encode.register(Message | bytes)
def encode_message(value):
    return "message"

event = Event()
print(encode(event))
Message.register(Event)
assert isinstance(event, Message)
print(encode(event))

Expected output:

default
message

Actual output:

default
default

Two controls isolate the problem. Removing the first print(encode(event)) makes the final call return "message". Keeping both calls and replacing the union decorator with stacked @encode.register(Message) and @encode.register(bytes) decorators also gives the expected result.

In Lib/functools.py, register() adds each union member to the registry, then checks the union object itself for __abstractmethods__. That misses the ABC member, so this dispatcher never starts checking abc.get_cache_token(). After Message.register(Event), isinstance() sees the new relationship while encode() continues using its cached fallback.

PEP 443 explicitly specifies cache invalidation when user code calls register() on an ABC: https://peps.python.org/pep-0443/#abstract-base-classes

CPython versions tested on:

3.11, 3.12, 3.13, 3.14, 3.15, 3.16, CPython main branch

Operating systems tested on:

Linux

Linked PRs

Activity

  1. added
    type-bug
    on Nov 26, 2026
  2. picnixz commented on Nov 26, 2026

    @picnixz
    Member

    I do not think this is a problem honestly. Unless the intent was to keep the cache synchronized this seems a normal limitation, same as when one unloads a module while some other references still exist in other modules.

  3. added
    stdlib
    pending
    on Nov 26, 2026
  4. picnixz commented on Nov 26, 2026

    @picnixz
    Member

    Ah I missed the fact that having a non-union approach works.

  5. removed
    pending
    on Nov 26, 2026
  6. Woojay44 commented on Nov 27, 2026

    @Woojay44

    I've opened #162717 with a fix (checking each union member for __abstractmethods__) and a regression test.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    stdlibtype-bug

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions