0

I'm making some experiments using attrs, but I'm experiencing some unexpected behaviors in the following code:

I created a class as this one:

@define
class User:
    name = field()
    errors = field(default=[])

    def compute_errors(self, error):
        self.errors.append(error)

Then I run the following script:

user1 = User(name="Miguel")

user1.compute_errors("Error 1")

user2 = User(name="Diogo")

print(user1)
print(user2)

The output is:

User(name='Miguel', errors=['teste'])
User(name='Diogo', errors=['teste'])

This is completely strange to me since user1 and user2 should be different objects. I've been reading the documentation but I'm not identifying any thing that mentions this. There's any explanation on that?

Update 1

I completely understand the explanation provided in this topic. However, I can't understand why this is applied to class attributes too. If I don't use attrs it works as expected. The errors list is empty in the instantiation of user2.

Update 3

I just find the answer to my question in this topic

Miguel Andrade
  • 346
  • 3
  • 13

0 Answers0