Skip to content

Migrate _pyi_private_set/get_type to TypeVar default for broader type checker support #2676

Closed
@huynguyengl99

Description

@huynguyengl99

Hi team,

Python 3.13 has added the default parameter for TypeVar (which we can use via typing_extensions for older Python versions).

With this feature, we can remove the fields _pyi_private_set_type, _pyi_private_get_type and the mypy plugin functions related to those.

For example, instead of:

class IntegerField(Field[_ST, _GT]):
    _pyi_private_set_type: float | int | str | Combinable
    _pyi_private_get_type: int
    _pyi_lookup_exact_type: str | int

We can define:

# **set** value type
_ST_Int = TypeVar("_ST_Int", contravariant=True, default=float | int | str | Combinable)
# **get** return type
_GT_Int = TypeVar("_GT_Int", covariant=True, default=int)

class IntegerField(models.Field[_ST_Int, _GT_Int]):
    _pyi_lookup_exact_type: str | int

By using this approach, we can eliminate the mypy plugin related to __pyi_private_set/get_type, allowing us to support other type checkers beyond mypy as well.

With this change, this code will work for all static type checkers:

my_num = IntegerField()

Rather than requiring:

my_num = IntegerField[float | int | str | Combinable, int]()

How do you think about this approach? I'm willing to create a PR for this improvement.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions