Created
May 24, 2024 23:13
-
-
Save mypy-play/2900368b3627fc43df48a551ca7d8702 to your computer and use it in GitHub Desktop.
Shared via mypy Playground
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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: ... | |
def __get__(self, instance: Any, owner: type | 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