-
as I'm from fairly old school Python where Python is not Java told us to not write getters and setters, upgrade to from typing import cast
class MyThing:
some_attr: bool
def __init__(self, some_attr: bool):
self.some_attr = some_attr
class MySubThing(MyThing):
@property
def some_attr(self) -> bool:
return cast(bool, self.__dict__['some_attr'])
@some_attr.setter
def some_attr(self, value: bool) -> None:
self.__dict__['some_attr'] = value
that is, for a family of classes, I don't want to impose the expense of anyway it seems like the above pattern isn't possible without putting the
Looking at some common workarounds, from typing import cast, TypeVar, Any
from typing import Protocol, overload
_T = TypeVar("_T")
class UpgradeDescriptor(Protocol[_T]):
@overload
def __get__(self, instance: None, owner: Any) -> _T:
...
@overload
def __get__(self, instance: object, owner: Any) -> _T:
...
def __set__(self, instance: Any, value: _T) -> None:
...
def __delete__(self, instance: Any) -> None:
...
class MyThing:
some_attr: UpgradeDescriptor[bool]
def __init__(self, some_attr: bool):
self.some_attr = some_attr
class MySubThing(MyThing):
@property
def some_attr(self) -> bool:
return cast(bool, self.__dict__["some_attr"])
@some_attr.setter
def some_attr(self, value: bool) -> None:
self.__dict__["some_attr"] = value
I can swap out that leaves us with the most succinct pattern is that we need two type-ignores: from typing import cast
class MyThing:
some_attr: bool
def __init__(self, some_attr: bool):
self.some_attr = some_attr
class MySubThing(MyThing):
@property # type: ignore[override]
def some_attr(self) -> bool: # type: ignore[override]
return cast(bool, self.__dict__['some_attr'])
@some_attr.setter
def some_attr(self, value: bool) -> None:
self.__dict__['some_attr'] = value is that the best we can do ? |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
|
Beta Was this translation helpful? Give feedback.
@property
should just work, and this is a known bug in mypy: python/mypy#4125