代码之家  ›  专栏  ›  技术社区  ›  beesleep

为weakref对象的列表定义python类型提示

  •  1
  • beesleep  · 技术社区  · 7 年前

    我还没有找到在使用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_list 是一个 list weakref MyObject ,类似于:

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

    ?

    1 回复  |  直到 7 年前
        1
  •  8
  •   Michael0x2a    7 年前

    我们可以通过咨询找到这些信息 typeshed

    具体来说,如果我们看一下 weakref module ref _weakref module . 从那里,我们看到了 定义为等同于 ReferenceType 威克雷夫 ).

    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 ).

    请注意 from __future__ import annotations

    from typing import List
    from weakref import ref
    
    # ...snip...
    
    my_list: "List[ReferenceType[MyObject]]" = [...]
    
    # Or:
    
    my_list: List["ReferenceType[MyObject]"] = [...]
    
    推荐文章