Skip to content

Instantly share code, notes, and snippets.

@mypy-play
Created May 24, 2024 23:09
Show Gist options
  • Save mypy-play/c1abd53c01034469e9253fffd23c6b90 to your computer and use it in GitHub Desktop.
Save mypy-play/c1abd53c01034469e9253fffd23c6b90 to your computer and use it in GitHub Desktop.
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: ...
def __get__(self, instance: Any, owner: type[Any] | None = None) -> T | Self:
return cast(T | Self, super().__get__(instance, owner))
def a_function(self) -> T: ...
def custom_property(type: type[T]) -> CustomProperty[T]:
return CustomProperty(type)
module_level = custom_property(int)
reveal_type(module_level) # CustomProperty[int]
reveal_type(module_level.a_function()) # int
class ClassWithCustomProperty:
property_holder = custom_property(int)
reveal_type(property_holder) # CustomProperty[int]
reveal_type(ClassWithCustomProperty.property_holder) # CustomProperty[int]
reveal_type(ClassWithCustomProperty().property_holder) # int
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment