gta*_*ico 5 python mypy python-typing
我查看了一些与使用带有描述符的打字相关的 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
Run Code Online (Sandbox Code Playgroud)
我以为我可以使用 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)
Run Code Online (Sandbox Code Playgroud)
您的解决方案很接近。为了让它完全工作,您只需要再做三处更改:
使整个 DataDescriptor 类通用,而不仅仅是它的方法。
当您在构造函数和方法签名中单独使用 TypeVar 时,您最终要做的是使每个方法独立通用。这意味着绑定到__init__T 的任何值实际上最终将完全独立于 T__get__将返回的任何值!
这与您想要的完全相反:您希望T不同方法之间的值完全相同。
要修复,请让 DataDescriptor 从Generic[T]. (在运行时,这与从 继承大致相同object。)
在 City 中,要么去掉两个字段的类型注释,要么分别将它们注释为 typeDataDescriptor[str]和DataDescriptor[float]。
基本上,这里发生的事情是您的字段本身实际上是 DataDescriptor 对象,并且需要这样注释。稍后,当您实际尝试使用您的city.zip_code和city.population字段时,mypy 会意识到这些字段是描述符,并使其类型成为您__get__方法的返回类型。
这种行为对应于运行时发生的情况:您的属性实际上是描述符,只有当您尝试访问这些属性时,您才会返回一个浮点数或一个 str 。
内的签名DataDescriptor.__init__,改变Type[T]要么Callable[[str], T],Callable[[Any], T]或Callable[[...], T]。
基本上,这样做Type[T]不起作用的原因是 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'
Run Code Online (Sandbox Code Playgroud)