Chao Xu
Chao Xu

Reputation: 2196

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?

Upvotes: 0

Views: 285

Answers (2)

balderman
balderman

Reputation: 23825

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)

Upvotes: 2

edward
edward

Reputation: 1

Though I don't know much about attr package. But I am pretty sure l is a static variable for the class List, which means it is not a member variable and it is shared across all the instances of List. You may want to make it become a member variable.

Upvotes: -1

Related Questions