Skip to content

Use of literal values in generic types #8605

Closed
@timfi

Description

@timfi

Hi, I was toying around with some typing in a small but "hacky" vector-maths module and found myself wondering if it was possible to make a generic type along the lines of Vector[3] where the 3 holds actual meaning/can be used in some fashion. I am unsure if this is possible with mypy as it stands now, and if not if this is something that is ever going to be possible (be it because it is "ugly" or outside of what mypy is trying to achieve).

For example some of such "vector-math-module" code could look like this:

class Vector(...):
    def __init__(self, *values: Union[float, int]):
        self._values = values

    def __add__(self: Vector[T], other: Vector[T]) -> Vector[T]:
        return Vector(*(a + b for a, b in zip(self._values, other._values)))

Vector(1, 2, 3) + Vector(1, 2, 3)
# -> mypy: ok

Vector(1, 2, 3) + Vector(1, 2)
# -> mypy: type mismatch

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