Skip to content

add PEP-585 support to singledispatch #131996

@deadPix3l

Description

@deadPix3l

Proposal: allow more specific dispatching using PEP-585 annotations

@dispatch.register
def _(arg: list[int|str]):
    return "this is a list of ints and strings!"

currently returns:

TypeError: Invalid annotation for 'arg'. list[int|str] is not a class.

This means we have to simplify the annotation at the expense of complicating the function, and less support for mypy:

@dispatch.register
def _(arg: list):
    # list[int|str]
    if all(isinstance(i, (int,str)) for i in arg):
        return "this is a list of ints and strings!"

    # elif <other types>:
        # other logic

    else:
        # list[any]

Personally I find this antitheitcal to singledispatch, which is supposed to solve this exact problem

Has this already been discussed elsewhere?

I have already discussed this feature proposal on Discourse

Links to previous discussion of this feature:

https://bugs.python.org/issue46191
https://discuss.python.org/t/singledispatch-support-for-pep-585-generic-types/86772

This does not seem to have wide support (yet), but its completely additional to the singledispatch decorator, and the non generic types will still work

Linked PRs

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions