python-attrs / cattrs

Composable custom class converters for attrs, dataclasses and friends.
https://catt.rs
MIT License
779 stars 108 forks source link

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

Closed jason-myers-klaviyo closed 4 months ago

jason-myers-klaviyo commented 4 months ago

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
Tinche commented 4 months ago

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 commented 4 months ago

Oh, and you'll need a changelog entry.

Tinche commented 4 months ago

Thanks a lot!