Search code examples
pythonpython-3.xpython-attrs

Why can I not add attributes to an attrs object?


Consider this example:

import attrs

@attrs.define(frozen=True)
class A:
    def __init__(self):
        object.__setattr__(self, "field", 1)

A()

This fails with an exception:

AttributeError: 'A' object has no attribute 'field'.

Why can I not add the field to the attrs object? Note of course that this does work when removing the attrs decorator.


Solution

  • Nevermind, I noticed that @attrs.define has slots=True as default argument. Passing slots=False resolves this issue. If slots=True, then the object will not have a __dict__ attribute and therefore setting the attribute will fail.