reduce overloads using TypeVarTuple and Unpack#48
reduce overloads using TypeVarTuple and Unpack#48michaeloliverx wants to merge 1 commit intohynek:mainfrom michaeloliverx:type-var-tuple
TypeVarTuple and Unpack#48Conversation
|
@hynek opened as a draft but what do you think? |
|
Wow if it worked reliably, that would be absolutely amazing. The question is how breaking it would be to say that this feature only works with Mypy 1.7(?) 🤔 |
Hard question to answer I am not sure, you can actually enable some support in the current version with:
I think I jumped the gun a bit, its not working as I expected 😢, there doesn't seem to be a way to express from typing import TypeVar, TypeVarTuple, Unpack, assert_type, overload
T = TypeVar("T")
Ts = TypeVarTuple("Ts")
@overload
def get(svc_type: type[T], /) -> T:
...
@overload
def get(*svc_types: Unpack[Ts]) -> tuple[Unpack[Ts]]:
...
def get(*svc_types: type) -> object:
"""
Get services of *svc_types*.
Instantiate them if necessary and register their cleanup.
Returns:
``svc_types[0]`` | ``tuple[*svc_types]``: If one service is
requested, it's returned directly. If multiple are requested, a
tuple of services is returned.
"""
...
a = get(int)
assert_type(a, int)
a, b, c = get(int, str, bool)
assert_type(a, int)
assert_type(b, str)
assert_type(c, bool)The return type is the same of what was passed i.e not an instance Close but not correct, maybe I will ask in the mypy issue tracker if its possible to express such a type. |
|
Aw, good luck! |
|
Yes unfortunately it is a limit of the type system, python/mypy#16394. Maybe some day. |
|
Thanks for trying tho; that would've been awesome! |
Summary
Reduce overloads for
getandagetand allow an unlimited number of service types to be returned.Uses PEP 646 – Variadic Generics which means
typing-extensionsis required for python versions below 3.11.Opened as a draft as mypy doesn't support
TypeVarTupleandUnpackyet but support has been merged python/mypy#16354.pyright has supported them for a while now.
Pull Request Check List
mainbranch – use a separate branch!docs/core-concepts.mdor one of the integration guides by hand.versionadded,versionchanged, ordeprecateddirectives..rstand.mdfiles is written using semantic newlines.