Skip to content

Instantly share code, notes, and snippets.

@mypy-play
mypy-play / main.py
Created July 22, 2024 12:22
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 July 22, 2024 11:38
Shared via mypy Playground
from typing import Literal, Optional, overload
@overload
def gimme(x: Literal[True]) -> str: ...
@overload
def gimme(x: Literal[False]) -> None: ...
@overload
def gimme(x: bool) -> Optional[str]: ...
def gimme(x: bool) -> Optional[str]:
@mypy-play
mypy-play / main.py
Created July 22, 2024 11:13
Shared via mypy Playground
from typing import Any
def foo(x: Any) -> None:
pass
class Bar():
pass
@mypy-play
mypy-play / main.py
Created July 22, 2024 10:48
Shared via mypy Playground
import typing as tp
if not tp.TYPE_CHECKING:
reveal_type = lambda var: var
class Foo: # Only supports "*Foo*".
def __init__(self, value: int) -> None:
self.value = value
def __add__(self, other: tp.Union["Foo", "FooBar"]) -> "Foo":
@mypy-play
mypy-play / main.py
Created July 22, 2024 08:43
Shared via mypy Playground
from fractions import Fraction
import decimal as dec
import typing as tp
if not tp.TYPE_CHECKING:
reveal_type = lambda var: var
Real = tp.Union[int, float, Fraction]
Decimal = tp.Union[dec.Decimal, int]
T1 = tp.TypeVar("T1", Real, Decimal)
@mypy-play
mypy-play / main.py
Created July 22, 2024 08:36
Shared via mypy Playground
from typing import Any
from dataclasses import is_dataclass
def example1(arg: Any) -> None:
if is_dataclass(arg):
reveal_type(arg) # ❌ Revealed type is "type[_typeshed.DataclassInstance]"
def example2(arg: object) -> None:
@mypy-play
mypy-play / main.py
Created July 22, 2024 06:00
Shared via mypy Playground
class Base:...
class Foo(Base):...
a: Base
b: int|None = {Foo:1}.get(type(a))
@mypy-play
mypy-play / main.py
Created July 22, 2024 03:58
Shared via mypy Playground
a: object = 1
reveal_type(a)
@mypy-play
mypy-play / main.py
Created July 22, 2024 00:59
Shared via mypy Playground
from typing import TypeVar
T1 = TypeVar("T1")
T2 = TypeVar("T2")
def f(t1: T1, t2: T2) -> T1 | T2:
return t1
@mypy-play
mypy-play / main.py
Created July 22, 2024 00:57
Shared via mypy Playground
from typing import TypeVar
T1 = TypeVar("T2")
T2 = TypeVar("T2")
def f(t1: T1, t2: T2) -> T1 | T2: ...
b: int = f(1, None) or 1