Skip to content

Feature: Use PEP 696 defaults for fields #1264

Open
@w0rp

Description

@w0rp

NOTE: This feature can't be worked on unless PEP 696 is accepted, but given its inclusion in typing_extensions I'd say it's likely it will be.

django-stubs uses set and get value generic types for fields, defined like so:

# __set__ value type
_ST = TypeVar("_ST", contravariant=True)
# __get__ return type
_GT = TypeVar("_GT", covariant=True)

class Field(RegisterLookupMixin, Generic[_ST, _GT]):

Specific field types use special attributes that the mypy plugin for django-stubs reads to fill in the get and set types with.

class CharField(Field[_ST, _GT]):
    _pyi_private_set_type: Union[str, int, Combinable]
    _pyi_private_get_type: str
    
    ...

This works for mypy, but not for other type checkers, where the generic parameters need to be written manually. To better support different type checkers, we could use the default values from PEP 696 instead.

_ST_CHAR = TypeVar("_ST_CHAR", contravariant=True, default=Union[str, int, Combinable])
_GT_CHAR = TypeVar("_GT_CHAR", covariant=True, default=str)

class CharField(Generic[_ST_CHAR, _GT_CHAR], Field[_ST_CHAR, _GT_CHAR]):
    ...

The mypy plugin could read the default values instead of the _pyi_private* attributes from before. For other type checkers, the instance values for __get__ and __set__ will then use the generic type defaults if not specified otherwise.

Metadata

Metadata

Assignees

No one assigned

    Labels

    enhancementNew feature or requestpyrightRelated to pyright type checker

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions