Created
February 8, 2022 07:19
-
-
Save technillogue/b82f8e93a84fa9501b4b07d07927c965 to your computer and use it in GitHub Desktop.
turns out generics work in python
This file contains hidden or 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
import asyncio | |
from typing import Generic, TypeVar | |
K = TypeVar("K") | |
V = TypeVar("V", str, list[str], dict[str, str], int, float) # some common simple JSON types | |
class SlowDict(Generic[K, V]): | |
def __init__(self) -> None: | |
self.d: dict[K, V] = {} | |
async def slow_get(self, key: K) -> V: | |
await asyncio.sleep(0.1) | |
return self.d[key] | |
async def slow_set(self, key: K, value: V) -> None: | |
await asyncio.sleep(0.1) | |
self.d[key] = value | |
async def main() -> None: | |
cache: SlowDict[str, str] = SlowDict() | |
await cache.slow_set("foo", "bar") | |
# error: Argument 2 to "slow_set" of "SlowMap" has incompatible type "List[int]"; expected "str" | |
await cache.slow_set("baz", [0]) | |
reveal_type(await cache.slow_get("foo")) | |
# note: Revealed type is 'builtins.str*' | |
(await cache.slow_get("foo")) + 1 | |
# error: Unsupported operand types for + ("str" and "int") | |
user_lists: SlowDict[str, list[str]] = SlowDict() | |
await user_lists.slow_set("foo", ["a"]) | |
reveal_type(await user_lists.slow_get("foo")) | |
# note: Revealed type is 'builtins.list*[builtins.str]' | |
await user_lists.slow_get("foo") > 1 | |
"a" in await user_lists.slow_get("foo") | |
# error: Unsupported operand types for > ("List[str]" and "int") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment