Код: Выделить всё
event_busКод: Выделить всё
from typing import TypeVar, Generic, Callable, Any
class EventBus:
def subscribe(self):
print("Subscribed")
def publish(self):
print("Published")
T = TypeVar('T')
def create_property(event_bus: EventBus):
class Property(Generic[T]):
def __init__(self, validator: Callable[[T], bool]):
self._validator = validator
def __set_name__(self, obj: Any, name: str):
self.name = name
def __get__(self, obj: Any, type: Any) -> T:
return obj.__dict__.get(self.name)
def __set__(self, obj: Any, value: T):
if not self._validator(value):
raise ValueError("Invalid value")
obj.__dict__[self.name] = value
event_bus.publish()
def property(validator: Callable[[T], bool] = lambda x: True) -> Property[T]:
return Property(validator)
return property
Код: Выделить всё
property: Callable[..., Property[T]] = create_property(event_bus.EventBus())
class MyComponent:
width = property() # Type of "width" is partially unknown
# Type of "width" is "Property[Unknown]
height: int = property(lambda x: x > 0) # Expression of type "Property[Unknown]" is
# incompatible with declared type "int"
Подробнее здесь: https://stackoverflow.com/questions/790 ... -in-python