Skip to content

Instantly share code, notes, and snippets.

@technillogue
Last active July 27, 2019 18:03
Show Gist options
  • Save technillogue/5841ed878701e7056765027ca4859e81 to your computer and use it in GitHub Desktop.
Save technillogue/5841ed878701e7056765027ca4859e81 to your computer and use it in GitHub Desktop.
example of stable protocols
from typing import Callable, TypeVar
from typing_extensions import Protocol
from cache import cache
X = TypeVar("X")
Y = TypeVar("Y")
Z = TypeVar("Z")
class Wrapper(Protocol):
__wrapped__: Callable
def compose(f: Callable[[Y], Z], g: Callable[[X], Y]) -> Callable[[X], Z]:
"""
Compose, but if either f or g are cached, the composed function will be cached,
but its calls will use the uncached versions of f and g.
"""
use_cache = False
if isinstance(f, Wrapper):
f = f.__wrapped__
use_cache = True
if isinstance(g, Wrapper):
g = g.__wrapped__
use_cache = True
def composed_function(arg: X) -> Z:
return f(g(arg))
composed_function.__name__ = composed_function.__qualname__ = "_".join(
(f.__name__, g.__name__)
)
if use_cache:
return cache.with_cache(composed_function)
return composed_function
from collections.abc import Sized
from typing import Iterator, Any
class FakeContainer:
def __init__(self, size: int) -> None:
self.size = size
def __len__(self) -> int:
return self.size
class BoolRepeater:
def __init__(self, repeat: bool) -> None:
self.repeat = repeat
def __next__(self) -> bool:
return self.repeat
def __iter__(self) -> BoolRepeater:
return self
def print_size(container: Sized) -> None:
print(len(container))
def print_next(iterable: Iterator) -> None:
print(next(iterable))
container = FakeContainer(3)
repeat_none = BoolRepeater(True)
print_size(container)
print_next(repeat_none)
try:
print_size(repeat_none)
except TypeError:
print("TypeError")
try:
print_next(container)
except TypeError:
print("TypeError")
test.py:37: error: Argument 1 to "print_size" has incompatible type "BoolRepeater"; expected "Sized"
test.py:41: error: Argument 1 to "print_next" has incompatible type "FakeContainer"; expected "Iterator[Any]"
3
True
TypeError
TypeError
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment