python 有没有一种方法可以在没有属性装饰器的情况下对类属性进行类型提示?

t5zmwmid  于 2024-01-05  发布在  Python
关注(0)|答案(3)|浏览(141)

考虑用Python编写一个接口类。接口将getter和setter方法隐藏在属性后面。有几个属性具有非常相似的结构,只是名称不同。为了减少代码重复,接口为其属性使用工厂方法:

  1. from __future__ import annotations
  2. class Interface:
  3. def property_factory(name: str) -> property:
  4. """Create a property depending on the name."""
  5. @property
  6. def _complex_property(self: Interface) -> str:
  7. # Do something complex with the provided name
  8. return name
  9. @_complex_property.setter
  10. def _complex_property(self: Interface, _: str):
  11. pass
  12. return _complex_property
  13. foo = property_factory("foo") # Works just like an actual property
  14. bar = property_factory("bar")
  15. def main():
  16. interface = Interface()
  17. interface.foo # Is of type '(variable) foo: Any' instead of '(property) foo: str'
  18. if __name__ == "__main__":
  19. main()

字符串
这个实现的一个问题是,Interface.fooInterface.bar将被标记为(variable) foo/bar: Any,即使它们应该是(property) foo/bar: str
使用内联类型提示,如

  1. foo: str = property_factory("foo")


感觉有点误导,因为foo不是一个真正的字符串。
我并不完全坚持这种属性模式。如果有更好的方法来创建属性,我也很乐意改变这种模式。但是,请记住,接口需要属性,因为真实的代码在getter/setter方法中做更复杂的事情。此外,我希望保留属性,而不是像get_property(self,name:str)这样的通用方法。
我也可以分享我正在处理的实际代码,上面的例子只是我想到的一个最小的例子。

cvxl0en2

cvxl0en21#

疯狂的猜测:property_factory被类型提示返回property;修饰的方法/函数的类型丢失,这通常不会发生,因为类型检查器也会检查它是否在类的主体中使用。
propertyis not generic(yet)。然而,链接问题的OP本身提供了一个property的泛型子类作为可能的解决方案。那是将近4年前的事情了,当时类型系统并不像现在这样好,所以让我们重写这个类:

  1. from typing import Any, Generic, TypeVar, overload, cast
  2. T = TypeVar('T') # The return type
  3. I = TypeVar('I') # The outer instance's type
  4. class Property(property, Generic[I, T]):
  5. def __init__(
  6. self,
  7. fget: Callable[[I], T] | None = None,
  8. fset: Callable[[I, T], None] | None = None,
  9. fdel: Callable[[I], None] | None = None,
  10. doc: str | None = None
  11. ) -> None:
  12. super().__init__(fget, fset, fdel, doc)
  13. @overload
  14. def __get__(self, instance: None, owner: type[I] | None = None) -> Callable[[I], T]:
  15. ...
  16. @overload
  17. def __get__(self, instance: I, owner: type[I] | None = None) -> T:
  18. ...
  19. def __get__(self, instance: I | None, owner: type[I] | None = None) -> Callable[[I], T] | T:
  20. return cast(Callable[[I], T] | T, super().__get__(instance, owner))
  21. def __set__(self, instance: I, value: T) -> None:
  22. super().__set__(instance, value)
  23. def __delete__(self, instance: I) -> None:
  24. super().__delete__(instance)

字符串
现在我们有了一个通用的property类,原始的设计可以重写为:
(The原创作品也是,只需要使用-> Property[Interface, str]/return Property(_getter, _setter)

  1. from collections.abc import Callable
  2. Getter = Callable[['Interface'], str]
  3. Setter = Callable[['Interface', str], None]
  4. def complex_property(name: str) -> tuple[Getter, Setter]:
  5. def _getter(self: Interface) -> str:
  6. ...
  7. def _setter(self: Interface, value: str) -> None:
  8. ...
  9. return _getter, _setter


.然后可以用作:

  1. class Interface:
  2. foo = Property(*complex_property("foo"))


假设bar是同一类的普通@property,下面是一些测试(mypy playgroundpyright playground):

  1. instance = Interface()
  2. reveal_type(Interface.foo) # expected: Any/property/Callable
  3. reveal_type(Interface.bar) # expected: Any/property/Callable
  4. reveal_type(instance.foo) # expected: str
  5. reveal_type(instance.bar) # expected: str
  6. instance.foo = 42 # expected: error
  7. instance.bar = 43 # expected: error
  8. instance.foo = 'lorem' # expected: fine
  9. instance.bar = 'ipsum' # expected: fine

展开查看全部
k10s72fa

k10s72fa2#

如果你不需要太多的特殊属性能力,你可以对任何变量、属性或属性使用类型提示,如下所示:

  1. class MyClass:
  2. '''Description of my class'''
  3. my_property: float = 5.6

字符串
在某些编辑器中,包括VSCode,您也可以在变量、属性或属性之后添加文档字符串。
(This总是有效的Python,但不是所有的编辑器都知道将文档字符串与变量/属性/属性相关联。尝试一下,看看它是否能在编辑器中工作。

  1. class MyClass:
  2. '''Description of my class'''
  3. my_property: float = 5.6
  4. '''Example description of `my_property`'''
  5. another_property: int = 4
  6. '''And another doc string here'''


下面是它在我的VSCode版本中的样子:x1c 0d1x

展开查看全部
balp4ylt

balp4ylt3#

在您当前的实现中,出现此问题是因为类型提示系统无法将property_factory创建的属性识别为具有特定类型的属性。解决此问题的一种方法是使用typing.cast函数将属性显式转换为所需类型。这样,您可以提供更准确的类型提示。
以下是如何修改代码:

  1. from __future__ import annotations
  2. from typing import cast
  3. class Interface:
  4. @staticmethod
  5. def property_factory(name: str) -> property:
  6. """Create a property depending on the name."""
  7. @property
  8. def _complex_property(self: Interface) -> str:
  9. # Do something complex with the provided name
  10. return name
  11. @_complex_property.setter
  12. def _complex_property(self: Interface, _: str):
  13. pass
  14. return cast(property, _complex_property)
  15. foo: str = property_factory("foo")
  16. bar: str = property_factory("bar")
  17. def main():
  18. interface = Interface()
  19. value: str = interface.foo # Now has the correct type hint
  20. if __name__ == "__main__":
  21. main()

字符串
在此修改中,我添加了cast(property,_complex_property)行,以显式地将创建的属性转换为属性类型。这允许您将foo和bar的类型提示指定为str。
虽然这解决了类型提示问题,但值得注意的是,使用强制转换本质上是告诉类型检查器信任您的Assert。因此,请确保实际实现符合指定的类型,以避免潜在的运行时错误。

展开查看全部

相关问题