Search code examples
pythonattr

attr library classes are sharing default value?


Here is an example of strange attr behavior.

import attr

@attr.s
class List:
  l = attr.ib(default=[])

a = List()
b = List()

a.l.append(1)

print(b.l)
# output is [1], this is unintuitive, why not []

Why is this happening, and how can I get the behavior that we obtain a new list each time?


Solution

  • The below code will create a 'private' list for each instance of List
    See here for the docs.

    import attr
    
    @attr.s
    class List:
      l = attr.ib(factory=list)