Why does Python not support record type? (i.e. mutable namedtuple)

后端 未结 11 1560
眼角桃花
眼角桃花 2020-12-12 22:10

Why does Python not support a record type natively? It\'s a matter of having a mutable version of namedtuple.

I could use namedtuple._replace. But I nee

11条回答
  •  自闭症患者
    2020-12-12 22:32

    This answer duplicates another one. There is a mutable alternative to collections.namedtuple - recordclass.

    It has same API and memory footprint as namedtuple (actually it also faster). It support assignments. 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)
    

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

提交回复
热议问题