-
The Python class C:
def __init__(self):
self._x = None
@property
def x(self):
"""I'm the 'x' property."""
return self._x
@x.setter
def x(self, value):
self._x = value
@x.deleter
def x(self):
del self._x what a neat pattern! so neat that when I saw this, I obviously assumed it was a standard Python idiom and it's what you see in SQLAlchemy's hybrid documentation, it works great and everybody uses it. However, when those of us outside of batteries included land try to use this pattern with tools like Mypy or Pyright, they give us the from typing import Any, Callable
# copied from builtins.pyi
class just_like_property:
fget: Callable[[Any], Any] | None
fset: Callable[[Any, Any], None] | None
fdel: Callable[[Any], None] | None
__isabstractmethod__: bool
def __init__(
self,
fget: Callable[[Any], Any] | None = ...,
fset: Callable[[Any, Any], None] | None = ...,
fdel: Callable[[Any], None] | None = ...,
doc: str | None = ...,
) -> None: ...
def getter(self, __fget: Callable[[Any], Any]) -> property: ...
def setter(self, __fset: Callable[[Any, Any], None]) -> property: ...
def deleter(self, __fdel: Callable[[Any], None]) -> property: ...
def __get__(self, __obj: Any, __type: type | None = ...) -> Any: ...
def __set__(self, __obj: Any, __value: Any) -> None: ...
def __delete__(self, __obj: Any) -> None: ...
class MyClass:
@property
def foo(self) -> int:
...
@foo.setter
def foo(self, value: int) -> None:
...
@just_like_property
def bar(self) -> int:
...
@bar.setter
def bar(self, value: int) -> None:
...
There's obviously several workarounds here, including class MyClass:
@just_like_property
def _inst_bar(self) -> int:
...
@_inst_bar.setter
def bar(self, value: int) -> None:
... This is sort of ugly, but if that's the state of things, it is what it is. If that's the best that can be done, I will proceed to be rewriting all my documentation examples to use a form more like the above that is type-checker friendly. questions:
thanks as always for all the great help I'm getting on these questions! |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 10 replies
-
I don't like this, because making a property read-only will no longer be simple as deleting the setter. It would be much better to get this fixed in mypy. But in my experience, mypy issues don't get fixed unless you're willing to fix things yourself :) If mypy isn't getting fixed any time soon, I would probably use |
Beta Was this translation helpful? Give feedback.
-
If your property is very very similar to
|
Beta Was this translation helpful? Give feedback.
@property
is hard-coded in the tools. It's unfortunate and creates several different kinds of issues for custom property classes and property-like classes. There have been attempts to reduce the special-casing, such as python/typeshed#5987.@property
is problematic, and making your own to replace it is fine.bar
is decorated with@bar.something
, without checking whether the first defini…