Skip to content

Instantly share code, notes, and snippets.

@henryiii
Last active December 10, 2020 18:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save henryiii/3505d39dc7ab1207d7fbed9349df7d3a to your computer and use it in GitHub Desktop.
Save henryiii/3505d39dc7ab1207d7fbed9349df7d3a to your computer and use it in GitHub Desktop.
MyPy and Vectors
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"))
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)
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"))
@henryiii
Copy link
Author

Just to be clear, these fail.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment