Skip to content

Instantly share code, notes, and snippets.

@mypy-play
mypy-play / main.py
Created May 25, 2024 04:17
Shared via mypy Playground
from typing import Literal, reveal_type
def sign(x: int) -> Literal[-1, 0, 1]:
"""Extracts the sign of x."""
s = -1 if x < 0 else (0 if x == 0 else 1)
reveal_type(s) # int
match s:
case -1 | 0 | 1:
reveal_type(s) # narrowed to Literal[-1, 0, 1]
return s
@mypy-play
mypy-play / main.py
Created May 24, 2024 23:13
Shared via mypy Playground
from typing import Any, cast, Generic, overload, Self, TypeVar
T = TypeVar('T')
class CustomProperty(property, Generic[T]):
@overload
def __get__(self, instance: None, owner: type | None = None, /) -> Self: ...
@overload
def __get__(self, instance: Any, owner: type | None = None, /) -> T: ...
@mypy-play
mypy-play / main.py
Created May 24, 2024 23:09
Shared via mypy Playground
from typing import Any, cast, Generic, overload, Self, TypeVar
T = TypeVar('T')
class CustomProperty(property, Generic[T]):
@overload # type: ignore[override]
def __get__(self, instance: None, owner: type[Any] | None, /) -> Self: ...
@overload
def __get__(self, instance: Any, owner: type[Any] | None, /) -> T: ...
@mypy-play
mypy-play / main.py
Created May 24, 2024 23:09
Shared via mypy Playground
from typing import Any, cast, Generic, overload, Self, TypeVar
T = TypeVar('T')
class CustomProperty(property, Generic[T]):
@overload # type: ignore[override]
def __get__(self, instance: None, owner: type[Any] | None, /) -> Self: ...
@overload
def __get__(self, instance: Any, owner: type[Any] | None, /) -> T: ...
@mypy-play
mypy-play / main.py
Created May 24, 2024 22:33
Shared via mypy Playground
t1 = ()
t2 = tuple()
reveal_type(t1) # tuple[()]
reveal_type(t2) # tuple[Any, ...]
foo = lambda: list(t1)
bar = lambda: list(t2)
qux = lambda: list(tuple())
@mypy-play
mypy-play / main.py
Created May 24, 2024 22:22
Shared via mypy Playground
# mypy: no-strict-optional
from typing import overload, Protocol
class Descriptor:
@overload
def __get__(self, instance: None, owner: type) -> int: ...
@overload
def __get__(self, instance: object, owner: type) -> str: ...
@mypy-play
mypy-play / main.py
Created May 24, 2024 22:00
Shared via mypy Playground
from typing import Protocol, final
@final
class Inter(Protocol):
x: int
def y(self) -> int:
...
@mypy-play
mypy-play / main.py
Created May 24, 2024 22:00
Shared via mypy Playground
from typing import Protocol, final
@final
class Inter(Protocol):
x: int
def y(self) -> int:
...
@property
@mypy-play
mypy-play / main.py
Created May 24, 2024 22:00
Shared via mypy Playground
class X:
val: object
class Y(X):
@property
def val(self) -> object:
return object()
@val.setter
def val(self, value):
self.x = True
@mypy-play
mypy-play / main.py
Created May 24, 2024 21:22
Shared via mypy Playground
from typing import Protocol, final
@final
class Inter(Protocol):
x: int
def y(self) -> int:
...
@property