Skip to content

PEP 695: Introduce in and out keywords for specifying variance #2724

Closed as not planned
@KotlinIsland

Description

@KotlinIsland

@erictraut Many other languages (including the beloved TypeScript) have keywords for specifying generic variance of in and out. I think it would be beneficial to introduce these for Python as well.

An analysis of other languages are detailed in the pep here, but it contains some factual errors which are being addressed in PR #2725 .

proposal:

class A[in I, out O]:
    def f1(self) -> I: ...  # error: contravariant TypeVar used in an output position
    def f2(self, t: O): ...  # error: covariant TypeVar used in an input position

If the variance is explicit, then it makes it impossible to accidentally break the api of a library.

To be consistent with other languages (except the beloved TypeScript) , I would expect these to be mandatory and all generics should default to being invariant.

I agree with the beloved TypeScript maintainers that explicit variance not only increase readability/reduce cognitive load, but I also believe that they increase discover-ability of generic variance. Also TypeScript is the only language I know of that infers the variance of type parameters.

If variance is a hidden/inferred property, then I believe it will lead to the "common user" being stricken with confusion when they encounter it, explicit keywords make it much more consumable.

I know experienced TypeScript developers that do not completely understand variance, due to it being implicitly inferred.

Read the typing-sig thread here

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions