Skip to content

Instantly share code, notes, and snippets.

@podhmo
Created Feb 23, 2020
Embed
What would you like to do?
class EnumerableMixin:
def map(self, fn):
return [fn(x) for x in self.each()]
class List(EnumerableMixin):
def __init__(self, xs):
self.xs = xs
def each(self):
return iter(self.xs)
print(List([10, 20, 30]).map(lambda x: x * x))
# [100, 400, 900]
import typing as t
A = t.TypeVar("A", covariant=True)
B = t.TypeVar("B")
class EnumerableMixin(t.Generic[A]):
def map(self, fn: t.Callable[[A], B]) -> t.List[B]:
return [fn(x) for x in self.each()]
class List(EnumerableMixin[A]):
def __init__(self, xs: t.List[A]) -> None:
self.xs = xs
def each(self) -> t.Iterator[A]:
return iter(self.xs)
L = List([10, 20, 30])
if t.TYPE_CHECKING:
reveal_type(L)
result = L.map(lambda x: x * x)
if t.TYPE_CHECKING:
reveal_type(result)
print(result)
import typing as t
import typing_extensions as tx
A = t.TypeVar("A", covariant=True)
B = t.TypeVar("B")
class HasEach(tx.Protocol[A]):
def each(self) -> t.Iterator[A]:
...
class EnumerableMixin(t.Generic[A]):
def map(self: HasEach[A], fn: t.Callable[[A], B]) -> t.List[B]:
return [fn(x) for x in self.each()]
class List(EnumerableMixin[A]):
def __init__(self, xs: t.List[A]) -> None:
self.xs = xs
def each(self) -> t.Iterator[A]:
return iter(self.xs)
L = List([10, 20, 30])
if t.TYPE_CHECKING:
reveal_type(L)
result = L.map(lambda x: x * x)
if t.TYPE_CHECKING:
reveal_type(result)
print(result)
import typing as t
import typing_extensions as tx
A = t.TypeVar("A", covariant=True)
B = t.TypeVar("B")
class HasEach(tx.Protocol[A]):
def each(self) -> t.Iterator[A]:
raise NotImplementedError("each")
class EnumerableMixin(HasEach[A]):
def map(self, fn: t.Callable[[A], B]) -> t.List[B]:
return [fn(x) for x in self.each()]
class List(EnumerableMixin[A]):
def __init__(self, xs: t.List[A]) -> None:
self.xs = xs
# def each(self) -> t.Iterator[A]:
# return iter(self.xs)
L = List([10, 20, 30])
if t.TYPE_CHECKING:
reveal_type(L)
result = L.map(lambda x: x * x)
if t.TYPE_CHECKING:
reveal_type(result)
print(result)
import typing_extensions as tx
class P(tx.Protocol):
def foo(self) -> str:
...
class M:
def bar(self: P) -> None:
print(self.foo(), self.foo())
# error: "P" has no attribute "boo"
print(self.boo())
def boo(self) -> str:
return "boo"
00:
mypy --strict $(shell echo $@*.py)
01:
mypy --strict $(shell echo $@*.py)
02:
mypy --strict $(shell echo $@*.py)
03:
mypy --strict $(shell echo $@*.py)
04:
mypy --strict $(shell echo $@*.py)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment