代码之家  ›  专栏  ›  技术社区  ›  Pro Q Rich Lysakowski PhD

如何键入具有特定结构的列表

  •  0
  • Pro Q Rich Lysakowski PhD  · 技术社区  · 5 年前

    我的代码中有一个数据结构(为了 MWE )是一个列表,其中第一个元素是字符串,第二个元素是整数。例如:

    foo: MyStructure = ["hello", 42] .

    现在,由于这个结构有一个排序,通常我会使用元组,而不是:

    foo: Tuple[str, int] = ("hello", 42)

    foo[0] = "goodbye" foo 是一个元组。

    键入此结构的最佳方法是什么?

    现在,我能想到的主要解决方案是不正确地键入结构,而是定义自己的结构,其真实类型在注释中列出:

    # MyStructure = [str, int]
    MyStructure = List[Union[str, int]]
    
    foo: MyStructure = ["hello", 42]
    

    有更好的办法吗?

    1 回复  |  直到 5 年前
        1
  •  1
  •   chepner    5 年前

    你不想要一个列表或元组;您需要一个表示产品类型级别的自定义类 str int . 数据类在这里特别有用。

    from dataclasses import dataclass
    
    
    @dataclass
    class MyStructure:
        first: str
        second: int
    
    
    foo: MyStructure = MyStructure("hello", 42)
    
    assert foo.first == "hello"
    assert foo.second = 42
    

    __getitem__ 类的方法:

    @dataclass
    class MyStructure:
        first: str
        second: int
    
        def __getitem__(self, key) -> Union[str,int]:
            if key == 0:
                return self.first
            elif key == 1:
                return self.second
            else:
                raise IndexError(key)
    

    另外,一个 MyStructure

    >>> foo = MyStructure("hello", 42)
    >>> import sys
    >>> sys.getsizeof(foo)
    48
    >>> sys.getsizeof(["hello", 42])
    72