簡體   English   中英

使用描述符進行類型提示

[英]Type hinting with descriptors

這個拉取請求中,似乎添加了對描述符的類型提示支持。

但是,似乎從未發布過最終的“正確”使用示例,也似乎從未將任何文檔添加到typing模塊Mypy 中

看起來正確的用法是這樣的

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 一起使用。 但是,下面的派生定義對我有用:

"""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))

問題中描述的方法似乎適用於 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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM