[英]How do you type hint an additional attribute on an object?
我有一个自定义测试运行程序,它使用 inspect 查找以test_
开头的所有函数。 有一次我向 function object 添加了一个属性。这样做是为了让测试运行器稍后可以访问文档字符串信息。
我真的很想为函数列表创建一个类型提示,以便我的 IDE (pycharm) 知道tdi
确实是 function object 的一个属性。
你如何构建这样的类型提示?
for m, fn in module.__dict__.items():
if m.startswith(prefix):
if callable(fn):
tdi = getTestDocInfo(fn) # reads the docstring for tags and puts the info in a dataclass
fn.tdi = tdi
tests.append(fn)
编辑:在这种情况下,类型提示应该传达 object 是 function 并且它具有属性tdi
。
正如@chepner 所指出的,类型提示的Protocol
构建块正是这里所需要的。
这是有效的。
@runtime_checkable
class TestFunc(Protocol):
tdi: TestDocInfo
def __call__(self, testresult: TestResult, shareditems: SharedItems): pass
tests: List[TestFunc]. #type hint I am looking for.
这似乎是typing.Protocol
和typing.runtime_checkable
的工作:
from typing import Protocol, runtime_checkable
@runtime_checkable
class HasTDI(Protocol):
tdi: int # Or whatever type is appropriate.
然后
isinstance(fn, HasTDI)
如果fn.tdi
存在并且是int
,则应该为真。
恐怕我不知道 PyCharm 是否会使用此信息。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.