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

Defining python type hints for list of a weakref object

我还没有找到如何在使用 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_listweakrefMyObjectlist,类似于:

my_list: List[Weakref[MyObject]] = [weakref.ref(o1), weakref.ref(o2)]

?

我们可以通过查阅 typeshed 找到此信息,这是一个标准库和一些流行的第 3 方模块的类型提示存储库。

具体来说,如果我们查看 weakref module, we can see that it re-exports ref from the _weakref module 的存根。从那里,我们看到 ref 被定义为等同于 ReferenceType class,它被定义为通用的(并且也从 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]"] = [...]