Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

GH-100623: Implement singledispatch on type/class arguments #100624

Conversation

smheidrich
Copy link
Contributor

gh-100623: Implement singledispatch on type/class arguments

This implements dispatching on arguments that are themselves types/classes in functools.singledispatch.

Lib/functools.py Outdated Show resolved Hide resolved
Comment on lines +2965 to +2974
@f.register
def _(arg: type[list|dict]):
return "type[list|dict]"

@f.register
def _(arg: type[set]|typing.Type[type(None)]):
return "type[set]|type[NoneType]"

self.assertEqual(f(list), "type[list|dict]")
self.assertEqual(f(type(None)), "type[set]|type[NoneType]")
Copy link
Contributor Author

@smheidrich smheidrich Dec 30, 2022

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm wondering if treating type[a|b] and type[a]|type[b] the same actually makes sense and even if so, whether union types should be supported for type[...] arguments at all:

E.g. if we have a single-dispatch function with an implementation for type[a|b|c], wouldn't people expect to be able to pass e.g. a|b to it and have it dispatch to that implementation? That would be much harder to implement than my current naive implementation of just splitting up unions into their individual constituent types, especially considering issubclass(a|b, a|b|c) isn't even possible.

So maybe unions of type[...]s and type[...]s of unions should just not be allowed for now, deferring them to when (if ever) issubclass supports these kinds of checks (or Python gets another issubtype function).

OTOH, it's unlikely that introducing support for dispatching to type[a|b|c] given a|b later on would be much of a breaking change... If only dispatching on single types is supported for now then that is all people will use, nobody will rely on the fact that a|b dispatches to the default implementation, they'll just never pass a|b to a single-dispatch function in the first place I should think. So it might be fine to implement it like this for now and leave only the "proper" handling for later.

@smheidrich
Copy link
Contributor Author

Closing, see #100623 (comment)

@smheidrich smheidrich closed this Jan 2, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging this pull request may close these issues.

3 participants