gpt4 book ai didi

python - 带有描述符的类型提示

转载 作者:行者123 更新时间:2023-11-28 18:59:27 25 4
gpt4 key购买 nike

this pull request看起来像是添加了对描述符的类型提示支持。

然而,看起来没有最终的“正确”用法示例被发布,也没有向 typing module 添加任何文档。或到 Mypy .

看起来正确的用法类似于this :

from typing import TypeVar

T = TypeVar('T')
V = TypeVar('V')


class classproperty():
def __init__(self, getter: Callable[[Type[T]], V]) -> None:
self.getter = getter

def __get__(self, instance: Optional[T], owner: Type[T]) -> V:
return self.getter(owner)


def forty_two(cls: Type) -> int:
return 42


class C:
forty_two: int = classproperty(forty_two)

这看起来合乎逻辑,但我不知道这是否真的是正确的做事方式。

有这方面的文档吗?还是实际适用于合并版本的完整示例?

最佳答案

问题中描述的方法似乎适用于 Mypy 和 PyCharm 类型检查器。

编辑:显然我的示例代码类型检查,但 MyPy 实际上无法推断版本 0.800 的类型。

"""Defines the `classproperty` decorator."""

from typing import Any, Callable, Optional, Type, TypeVar


T = TypeVar("T")
V = TypeVar("V")


class classproperty(property):
"""Class property decorator."""

def __init__(self, getter: Callable[[Any], V]) -> None:
"""Override getter."""
self.getter = getter # type: ignore

def __get__(self, instance: Optional[T], owner: Type[T]) -> V: # type: ignore
return self.getter(owner) # type: ignore

def __set__(self, obj, value):
super(classproperty, self).__set__(type(obj), value)

def __delete__(self, obj):
super(classproperty, self).__delete__(type(obj))


class Thing:
@classproperty
def value1(cls) -> int:
return 44

value2 = classproperty(lambda cls: 55)

@property
def value3(self) -> int:
return 66


thing = Thing()
reveal_type(thing.value1)
reveal_type(thing.value2)
reveal_type(thing.value3)
main.py:40: note: Revealed type is '<nothing>'
main.py:41: note: Revealed type is '<nothing>'
main.py:42: note: Revealed type is 'builtins.int'

https://mypy-play.net/?mypy=0.800&python=3.9&gist=79f6fab466ecc4c4b45b75f1c7b6a6a8 .

关于python - 带有描述符的类型提示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54413434/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com