PEP 696 - default inferred Generic
I don't see an example in the PEP that shows using a default inferred through an __init__() method, and just wanted to check if this would work as expected. Specifically, if I want to have a default value for a Generic, currently I need to use overloads like this: ResponseT = TypeVar("ResponseT", bound=AbstractClientResponse) class ClientSession(Generic[ResponseT]): @overload def __init__(self, response_class: type[ResponseT]): ... @overload def __init__(self: ClientSession[ClientResponse]): ... def __init__(self, response_class: type[ResponseT] = ClientResponse): ... This becomes unwieldy when you have many extra arguments to be maintained in the overloads and exponentially more complex when you add additional types to be generic over (e.g. 8 overloads are needed for a 3 item Generic). Both of these cases are true of aiohttp's ClientSession, which we are looking at improving typing for. With default, I'm hoping that this will work without overloads with just: ResponseT = TypeVar("ResponseT", bound=AbstractClientResponse, default=ClientResponse) class ClientSession(Generic[ResponseT]): def __init__(self, response_class: type[ResponseT] = ClientResponse): ... ClientSession(CustomResponse) # -> ClientSession[CustomResponse] ClientSession() # -> ClientSession[ClientResponse] Can anyone confirm if that is expected to work or not? Might be good if the type checker could even verify the parameter default matches the TypeVar default (though there's probably cases where you have None for the parameter and want it to default to another type...). Thanks, Sam
Hi, Yes this certainly should work, if you wish to try any PEP 696 related features, I have a prototype in mypy for this https://github.com/Gobot1234/mypy/tree/TypeVar-defaults and if mypy isn't your cup of tea, pyright/pylance has basic support for PEP 696 already. You need to import TypeVar from typing_extensions if you want anything to work at runtime however.
participants (2)
-
James H-B
-
Sam Bull