How to supply default values to mutable attributes using python attrs?

1.4k views Asked by At

Just started using python attr, which looks great. The package allows the easy creation of empty mutable parameters by using a factory to create new objects, but the intended method of populating these empty objects with default values isn't clear to me. For example, this works to create a new list with a default value, but the default gets lost in the method call:

import attr; import typing

@attr.s(auto_attribs=True)
class C:
    x: int=66
    # I want loi as a list with default value [1,2,3]
    loi: typing.List[int] = attr.Factory(list)

    def __attrs_post_init__(self):
        self.loi.extend([1,2,3])

cx = C()
cx.loi = [1,2,3]
0

There are 0 answers