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

Add cattrs support for TypeVar with default (PEP696) #512

Merged

Conversation

jason-myers-klaviyo
Copy link
Contributor

@jason-myers-klaviyo jason-myers-klaviyo commented Feb 25, 2024

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:

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

Change

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

@jason-myers-klaviyo jason-myers-klaviyo changed the title Add support for TypeVar with default (PEP696) Add cattrs support for TypeVar with default (PEP696) Feb 25, 2024
@jason-myers-klaviyo jason-myers-klaviyo marked this pull request as ready for review February 25, 2024 14:24
@Tinche
Copy link
Member

Tinche commented Feb 25, 2024

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.

@Tinche Tinche added this to the 24.1 milestone Feb 25, 2024
@Tinche
Copy link
Member

Tinche commented Feb 25, 2024

Oh, and you'll need a changelog entry.

@Tinche
Copy link
Member

Tinche commented Mar 1, 2024

Thanks a lot!

@Tinche Tinche merged commit 2b10bcb into python-attrs:main Mar 1, 2024
8 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants