首页 > 解决方案 > 将 Typing 和 Mypy 与描述符一起使用

问题描述

我查看了一些与使用带有描述符的打字相关的 SO 帖子和 github 问题,但我无法解决我的问题。

我有包装类,我想将属性定义为可以获取和“转换”内部数据结构的属性的描述。

class DataDescriptor(object):
    def __init__(self, name: str, type_):
        self.name = name
        self.type_ = type_

    def __get__(self, instance, cls):
        if not instance:
            raise AttributeError("this descriptor is for instances only")
        value = getattr(instance._data, self.name)
        return self.type_(value)


class City(object):
    zip_code: str = DataDescriptor("zip_code", str)
    # mypy: Incompatible types in assignment

    population: float = DataDescriptor("population", float)
    # mypy: Incompatible types in assignment

    def __init__(self, data):
        self._data = data


class InternalData:
    # Will be consumed through city wrapper
    def __init__(self):
        self.zip_code = "12345-1234"
        self.population = "12345"
        self.population = "12345"


data = InternalData()
city = City(data)
assert city.zip_code == "12345-1234"
assert city.population == 12345.0

我想我也许可以使用 TypeVar,但我无法理解它。

这就是我尝试过的——我想我可以动态地描述描述符将采用“类型”,而这种类型也是__get__将返回的类型。我在正确的轨道上吗?

from typing import TypeVar, Type
T = TypeVar("T")


class DataDescriptor(object):
    def __init__(self, name: str, type_: Type[T]):
        self.name = name
        self.type_ = type_

    def __get__(self, instance, cls) -> T:
        if not instance:
            raise AttributeError("this descriptor is for instances only")
        value = getattr(instance._data, self.name)
        return self.type_(value)
        # Too many arguments for "object"mypy(error)

标签: pythonmypypython-typing

解决方案


您的解决方案很接近。为了让它充分发挥作用,您只需要再进行三项更改:

  1. 使您的整个 DataDescriptor 类通用,而不仅仅是它的方法。

    当您在构造函数和方法签名中单独使用 TypeVar 时,您最终要做的是使每个方法独立地通用。这意味着绑定到__init__T 的任何值实际上最终将完全独立于 T__get__将返回的任何值!

    这与您想要的完全相反:您希望T不同方法之间的值完全相同。

    要修复,请让 DataDescriptor 继承自Generic[T]. (在运行时,这与从 . 继承基本相同object。)

  2. 在 City 中,要么去掉两个字段的类型注释,要么分别将它们注释为类型DataDescriptor[str]DataDescriptor[float]

    基本上,这里发生的事情是您的字段本身实际上是 DataDescriptor 对象,并且需要这样注释。稍后,当您实际尝试使用city.zip_codeandcity.population字段时,mypy 会意识到这些字段是描述符,并使其类型成为您__get__方法的返回类型。

    此行为对应于运行时发生的情况:您的属性实际上是描述符,并且只有在您尝试访问这些属性时才会返回浮点数或 str。

  3. 在 的签名中DataDescriptor.__init__,更改Type[T]Callable[[str], T]Callable[[Any], T]Callable[[...], T]

    Type[T]基本上,doing不起作用的原因是 mypy 并不确切知道Type[...]您可能会提供什么样的对象。例如,如果你尝试做会发生什么foo = DataDescriptor('foo', object)?这将导致__get__调用object("some value"),这会在运行时崩溃。

    因此,让我们让您的 DataDescriptor 接受任何类型的转换器函数。根据您的需要,您可以让您的转换器函数只接受一个字符串 ( Callable[[str], T])、任何任意类型的任何单个参数 ( Callable[[Any], T]) 或任意数量的任意类型的参数 ( Callable[..., T])。

将这些放在一起,您的最终示例将如下所示:

from typing import Generic, TypeVar, Any, Callable

T = TypeVar('T')

class DataDescriptor(Generic[T]):
    # Note: I renamed `type_` to `converter` because I think that better
    # reflects what this argument can now do.
    def __init__(self, name: str, converter: Callable[[str], T]) -> None:
        self.name = name
        self.converter = converter

    def __get__(self, instance: Any, cls: Any) -> T:
        if not instance:
            raise AttributeError("this descriptor is for instances only")
        value = getattr(instance._data, self.name)
        return self.converter(value)


class City(object):
    # Note that 'str' and 'float' are still valid converters -- their
    # constructors can both accept a single str argument.
    #
    # I also personally prefer omitting type hints on fields unless
    # necessary: I think it looks cleaner that way.
    zip_code = DataDescriptor("zip_code", str)
    population = DataDescriptor("population", float)

    def __init__(self, data):
        self._data = data


class InternalData:
    def __init__(self):
        self.zip_code = "12345-1234"
        self.population = "12345"
        self.population = "12345"


data = InternalData()
city = City(data)

# reveal_type is a special pseudo-function that mypy understands:
# it'll make mypy print out the type of whatever expression you give it.
reveal_type(city.zip_code)    # Revealed type is 'str'
reveal_type(city.population)  # Revealed type is 'float'

推荐阅读