Closed jason-myers-klaviyo closed 4 months ago
This adds support for TypeVars with default values, as defined in PEP 696. This PEP was recently recommended by the typing council to be accepted, and is currently already available via typing_extensions.TypeVar (see test case)
typing_extensions.TypeVar
Essentially if you have a generic class:
from attrs import define from typing import TypeVar T = TypeVar("T") @define class C(Generic[T]): a: T
You must specify the generic type to use it:
@define class Foo: c: C[str] # C.a = str
While this causes is an error when structuring (as expected):
@define class Foo: c: C # C.a = ?
Since we don't know what type to use for T in C
T
C
PEP 696 allows you to set a default type that is used if the generic type is not specified, so this becomes possible:
from attrs import define from typing_extensions import TypeVar T = TypeVar("T", default=str) # This part is new @define class C(Generic[T]): a: T
And you can now use C directly without specifying a type, and the type will be defaulted:
@define class Foo: c: C # C.a = str @define class Bar: c: C[int] # C.a = int
Oh nice, I've been waiting for this for some of my other projects. I'm swamped at work though so I might take a little while to get to this.
Oh, and you'll need a changelog entry.
Thanks a lot!
Purpose
This adds support for TypeVars with default values, as defined in PEP 696. This PEP was recently recommended by the typing council to be accepted, and is currently already available via
typing_extensions.TypeVar
(see test case)Background
Essentially if you have a generic class:
You must specify the generic type to use it:
While this causes is an error when structuring (as expected):
Since we don't know what type to use for
T
inC
Change
PEP 696 allows you to set a default type that is used if the generic type is not specified, so this becomes possible:
And you can now use
C
directly without specifying a type, and the type will be defaulted: