gpt4 book ai didi

Python 类型检查协议(protocol)和描述符

转载 作者:行者123 更新时间:2023-12-05 05:57:53 26 4
gpt4 key购买 nike

当涉及描述符时,我观察到关于 typing.Protocol 的行为,我不太理解。考虑以下代码:

import typing as t

T = t.TypeVar('T')


class MyDescriptor(t.Generic[T]):

def __set_name__(self, owner, name):
self.name = name

def __set__(self, instance, value: T):
instance.__dict__[self.name] = value

def __get__(self, instance, owner) -> T:
return instance.__dict__[self.name]


class Named(t.Protocol):

first_name: str


class Person:

first_name = MyDescriptor[str]()
age: int

def __init__(self):
self.first_name = 'John'


def greet(obj: Named):
print(f'Hello {obj.first_name}')


person = Person()
greet(person)

Person 是否隐式实现了 Named 协议(protocol)? According to mypy, it isn't :

error: Argument 1 to "greet" has incompatible type "Person"; expected "Named"
note: Following member(s) of "Person" have conflicts:
note: first_name: expected "str", got "MyDescriptor[str]"

我想那是因为 mypy 很快得出结论,strMyDescriptor[str] 只是两种不同的类型。很公平。

但是,为 first_name 使用普通的 str 或将其包装在获取和设置 str 的描述符中只是一个实现细节。此处的鸭式输入告诉我,我们将使用 first_name(界面)的方式不会改变。

换句话说,Person 实现了 Named

作为旁注,PyCharm 的类型检查器在这种特殊情况下不会发出错误提示(尽管我不确定这是设计使然还是偶然)。

根据typing.Protocol的预期用途,我的理解有误吗?

最佳答案

我正在努力寻找它的引用,但我认为 MyPy 在描述符的一些更精细的细节方面有点困难(你可以理解为什么,那里有相当多的魔法)。我认为这里的解决方法就是使用 typing.cast:

import typing as t

T = t.TypeVar('T')


class MyDescriptor(t.Generic[T]):
def __set_name__(self, owner, name: str) -> None:
self.name = name

def __set__(self, instance, value: T) -> None:
instance.__dict__[self.name] = value

def __get__(self, instance, owner) -> T:
name = instance.__dict__[self.name]
return t.cast(T, name)


class Named(t.Protocol):
first_name: str


class Person:
first_name = t.cast(str, MyDescriptor[str]())
age: int

def __init__(self) -> None:
self.first_name = 'John'


def greet(obj: Named) -> None:
print(f'Hello {obj.first_name}')


person = Person()
greet(person)

passes MyPy .

关于Python 类型检查协议(protocol)和描述符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68677919/

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