Last active
December 10, 2020 18:14
MyPy and Vectors
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from __future__ import annotations # type: ignore | |
from typing import Protocol, TypeVar, Generic | |
T = TypeVar("T") | |
U = TypeVar("U") | |
V = TypeVar("V") | |
W = TypeVar("W") | |
class Addable(Protocol[W]): | |
def __add__(self, other: W) -> W: ... | |
class Vector(Protocol[T]): | |
x: T | |
y: T | |
def __init__(self, x: T, y: T) -> None: | |
... | |
def free_add(a: Vector[Addable[V]], b: Vector[Addable[V]]) -> Vector[Addable[V]]: | |
return a.__class__(a.x + b.x, a.y + b.y) | |
class RealVector(Generic[U]): | |
def __init__(self, x: U, y: U) -> None: | |
self.x = x | |
self.y = y | |
free_add(RealVector(1,2), RealVector(3,4)) | |
free_add(RealVector(1,2), RealVector("hi", "hello")) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from typing import Protocol, TypeVar | |
T = TypeVar("T") | |
class Vector(Protocol[T]): | |
x: T | |
y: T | |
def __init__(self, x: T, y: T) -> None: ... | |
def free_add(a: Vector[T], b: Vector[T]) -> Vector[T]: | |
return a.__class__(a.x + b.x, a.y + b.y) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from __future__ import annotations # type: ignore | |
from typing import Protocol, TypeVar, Generic | |
T = TypeVar("T", covariant=True) | |
U = TypeVar("U") | |
V = TypeVar("V") | |
W = TypeVar("W") | |
class Addable(Protocol[W]): | |
def __add__(self, other: W) -> W: ... | |
class Vector(Protocol[T]): | |
x: Addable | |
y: Addable | |
def __init__(self, x: T, y: T) -> None: | |
... | |
def free_add(a: Vector[V], b: Vector[V]) -> Vector[V]: | |
return a.__class__(a.x + b.x, a.y + b.y) | |
class RealVector(Generic[U]): | |
def __init__(self, x: U, y: U) -> None: | |
self.x = x | |
self.y = y | |
free_add(RealVector(1,2), RealVector(3,4)) | |
free_add(RealVector(1,2), RealVector("hi", "hello")) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Just to be clear, these fail.