Skip to content

Instantly share code, notes, and snippets.

@mypy-play
mypy-play / main.py
Created January 26, 2026 07:09
Shared via mypy Playground
from __future__ import annotations
import re
import uuid
from dataclasses import dataclass, field, replace
from datetime import date, datetime, UTC
from typing import Optional, Self, Literal
def _normalize(value: str) -> str:
@mypy-play
mypy-play / main.py
Created January 25, 2026 15:21
Shared via mypy Playground
from dataclasses import dataclass, field
from typing import TYPE_CHECKING
@dataclass
class NormalDataClass():
a : str
b : int
c : int = field(init=False)
NormalDataClass(a='', b=0, c=0)
@mypy-play
mypy-play / main.py
Created January 25, 2026 14:49
Shared via mypy Playground
from typing import reveal_type
import random
def choice[T](left: T, right: T) -> T:
if random.random() < 0.5:
return left
else:
return right
reveal_type(choice(3, "hey!"))
@mypy-play
mypy-play / main.py
Created January 25, 2026 13:00
Shared via mypy Playground
from collections.abc import Callable
from typing import reveal_type
class Foo:
def __init__(self, size: str) -> None:
self.size = size
def create_big_foo() -> Foo:
return Foo('big')
@mypy-play
mypy-play / main.py
Created January 25, 2026 11:10
Shared via mypy Playground
from typing import Any, Optional, cast, TypeVar, reveal_type
## Case 1: type variable in return position of function
def f[T]() -> T:
raise Exception()
# mypy correctly refuses to type this, as it cannot infer T from the call site.
reveal_type(f())
@mypy-play
mypy-play / main.py
Created January 25, 2026 01:28
Shared via mypy Playground
from typing import Any, Optional, cast, TypeVar, reveal_type
## Case 1: type variable in return position of function
def f[T]() -> T:
raise Exception()
# mypy correctly refuses to type this, as it cannot infer T from the call site.
reveal_type(f())
@mypy-play
mypy-play / main.py
Created January 24, 2026 18:56
Shared via mypy Playground
from __future__ import annotations
from typing import overload, Iterator
class Foo:
@overload
def method(self: Bar) -> Iterator[Bar]: ...
@overload
def method(self: Foo) -> Iterator[Foo]: ...
def method(self) -> Iterator[Foo] | Iterator[Bar]:
raise NotImplementedError
@mypy-play
mypy-play / main.py
Created January 24, 2026 18:30
Shared via mypy Playground
from typing import Protocol
class P(Protocol):
def not_abstractmethod(self): ...
class Q(P): ...
Q()
@mypy-play
mypy-play / main.py
Created January 24, 2026 09:15
Shared via mypy Playground
from typing import Callable
class C[T]: ...
def f[U]() -> type[C[U]]:
return C
c: Callable[[], C[int]] = f()
reveal_type(f)
reveal_type(c)
@mypy-play
mypy-play / main.py
Created January 24, 2026 09:14
Shared via mypy Playground
from typing import Callable
class C[T]: ...
def f[U]() -> type[C[U]]:
return C
c: Callable[[], C[int]] = f()
reveal_type(f)
reveal_type(c)