Skip to content

functools.singledispatch registration prioritizes the types of normal arguments before positional-only ones #143886

Description

@pR0Ps

Bug report

Bug description:

Decorator-based functools.singledispatch registration prioritizes the types of normal arguments before positional-only ones when getting "the type of the first argument".

This means that a function of def f(pos: str, /, other: int) will be registered to be dispatched for other's type (int) instead of pos (str).

To reproduce:

import functools

@functools.singledispatch
def f(arg, /, extra):
    return f"{arg}: undispatched type"

@f.register
def f_int(arg: int, /, extra: str):
    return f"{arg} is a {type(arg)} (dispatched by int)"

@f.register
def f_str(arg: str, /, extra: int):
    return f"{arg} is a {type(arg)} (dispatched by str)"

print(f(None, "extra"))
print(f(1, "extra"))
print(f("s", "extra"))

Result:

None: undispatched type
1 is a <class 'int'> (dispatched by str)
s is a <class 'str'> (dispatched by int)

Expected:

None: undispatched type
1 is a <class 'int'> (dispatched by int)
s is a <class 'str'> (dispatched by str)

CPython versions tested on:

3.9, 3.10, 3.11, 3.12, 3.13, 3.14, CPython main branch

Operating systems tested on:

macOS

Linked PRs

Activity

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

    3.13bugs and security fixes3.14bugs and security fixes3.15pre-release feature fixes, bugs and security fixesstdlibStandard Library Python modules in the Lib/ directorytype-bugAn unexpected behavior, bug, or error

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions