为弱引用对象的列表定义python类型提示

时间:2018-09-27 01:46:23

标签: python weak-references type-hinting

我还没有发现在使用weakrefs时如何给类型提示指示。

from typing import List
import weakref
class MyObject:
    def __init(self, foo)
        self.foo = foo
o1 = MyObject(1)
o2 = MyObject(2)
my_list: List[weakref] = [weakref.ref(o1), weakref.ref(o2)]

有没有办法说my_listlistweakref的{​​{1}},就像这样:

MyObject

1 个答案:

答案 0 :(得分:3)

我们可以通过咨询typeshed来找到此信息,{{3}是标准库的类型提示存储库和一些流行的第三方模块。

具体来说,如果我们查看weakref module的存根,我们可以看到它从_weakref module重新导出ref。从那里,我们看到ref被定义为等同于ReferenceType类,该类被定义为通用类(并且也从weakref重新导出)。

将这些部分放在一起,我们可以为您的my_list变量提供如下类型的提示:

from __future__ import annotations
from typing import List
from weakref import ref, ReferenceType

# ...snip...

my_list: List[ReferenceType[MyObject]] = [...]

有趣的是,这样做也是可以的:

from __future__ import annotations
from typing import List
from weakref import ref

# ...snip...

my_list: List[ref[MyObject]] = [...]

基本上,ref也是ReferenceType的别名,因此我们可以互换使用这两种类型。

我个人会使用ReferenceType,但这主要是因为我已经习惯了以大写字母开头的类型。 (或者,如果该类型提示开始变得太冗长,我可能会定义一个自定义类型别名Ref = ReferenceType。)

请注意,from __future__ import annotations行仅在Python 3.7+上可用。如果您使用的是旧版本的Python,则需要手动将类型提示设置为字符串:

from typing import List
from weakref import ref

# ...snip...

my_list: "List[ReferenceType[MyObject]]" = [...]

# Or:

my_list: List["ReferenceType[MyObject]"] = [...]
相关问题