Existence of mutable named tuple in Python?

前端 未结 10 2156
旧巷少年郎
旧巷少年郎 2020-11-29 16:23

Can anyone amend namedtuple or provide an alternative class so that it works for mutable objects?

Primarily for readability, I would like something similar to namedt

10条回答
  •  自闭症患者
    2020-11-29 17:08

    There is a mutable alternative to collections.namedtuple - recordclass.

    It has the same API and memory footprint as namedtuple and it supports assignments (It should be faster as well). For example:

    from recordclass import recordclass
    
    Point = recordclass('Point', 'x y')
    
    >>> p = Point(1, 2)
    >>> p
    Point(x=1, y=2)
    >>> print(p.x, p.y)
    1 2
    >>> p.x += 2; p.y += 3; print(p)
    Point(x=3, y=5)
    

    For python 3.6 and higher recordclass (since 0.5) support typehints:

    from recordclass import recordclass, RecordClass
    
    class Point(RecordClass):
       x: int
       y: int
    
    >>> Point.__annotations__
    {'x':int, 'y':int}
    >>> p = Point(1, 2)
    >>> p
    Point(x=1, y=2)
    >>> print(p.x, p.y)
    1 2
    >>> p.x += 2; p.y += 3; print(p)
    Point(x=3, y=5)
    

    There is a more complete example (it also includes performance comparisons).

    Since 0.9 recordclass library provides another variant -- recordclass.structclass factory function. It can produce classes, whose instances occupy less memory than __slots__-based instances. This is can be important for the instances with attribute values, which has not intended to have reference cycles. It may help reduce memory usage if you need to create millions of instances. Here is an illustrative example.

提交回复
热议问题