Skip to content

Instantly share code, notes, and snippets.

@mypy-play
mypy-play / main.py
Created May 5, 2024 15:51
Shared via mypy Playground
import typing as t
from dataclasses import dataclass
if t.TYPE_CHECKING:
base = t.Tuple[str, bool]
else:
base = object
@dataclass
@mypy-play
mypy-play / main.py
Created May 5, 2024 15:34
Shared via mypy Playground
from typing import TYPE_CHECKING, TypeVar, Generic
from typing_extensions import reveal_type
T1 = TypeVar("T1")
T2 = TypeVar("T2")
if TYPE_CHECKING:
# This is how Group looks like to the type checker
class Group(tuple[T1, T2], Generic[T1, T2]):
def __new__(cls, key: T1, group: T2) -> "Group[T1, T2]": ...
@mypy-play
mypy-play / main.py
Created May 5, 2024 13:06
Shared via mypy Playground
from dataclasses import dataclass
@dataclass
class Test:
text: str
@staticmethod
def gen_text() -> Text:
return Test("some text")
@mypy-play
mypy-play / main.py
Created May 5, 2024 00:43
Shared via mypy Playground
from typing import Iterator
def fib(n: int) -> Iterator[int]:
a, b = 0, 1
while a < n:
yield a
a, b = b, a + b
@mypy-play
mypy-play / main.py
Created May 4, 2024 14:08
Shared via mypy Playground
from typing import Generic, TypeVar
T = TypeVar("T", contravariant=True)
class N(Generic[T]): ...
class C(N[N["C"]]): ...
x: N[C] = C()
@mypy-play
mypy-play / main.py
Created May 3, 2024 21:03
Shared via mypy Playground
from typing import *
from pathlib import Path
T = TypeVar("T")
def reverse_directory_search(filename: str, search_base: Path) -> Optional[Path]:
"""Search backwards for a file starting on a given directory.
E.g.: from /a/b/c a file d.txt will be checked in the following order:
- /a/b/c/d.txt
@mypy-play
mypy-play / main.py
Created May 3, 2024 20:16
Shared via mypy Playground
from typing import Any, Generic, TypeVar
_T = TypeVar("_T")
_U = TypeVar("_U", covariant=True)
class Node(Generic[_T, _U]):
children: "dict[str, Node[_U, object]]"
def __init__(self, children: "dict[str, Node[_U, object]]"):
self.children = children
@mypy-play
mypy-play / main.py
Created May 3, 2024 15:19
Shared via mypy Playground
from typing import Callable
def dec(f) -> Callable[[int], None]: raise NotImplementedError
if int():
def f(x: str): pass
else:
@dec
def f() -> None: pass
@mypy-play
mypy-play / main.py
Created May 3, 2024 12:29
Shared via mypy Playground
from typing import Literal
from typing_extensions import assert_never
def doit_if(result: Literal[1, -1]) -> None:
if result == 1:
pass
elif result == -1:
reveal_type(result)
else:
@mypy-play
mypy-play / main.py
Created May 3, 2024 09:25
Shared via mypy Playground
from typing import (
Generic,
TypeVar,
Callable,
Concatenate,
ParamSpec,
reveal_type,
)
from dataclasses import dataclass