Skip to content

Thoughts on immutability #50

@Tinche

Description

@Tinche

Hi,

working on making Attributes immutable, and also thinking about immutability in Python in general, to evaluate how hard would it be to actually allow attrs to create immutable classes.

(Side note: adding __slots__ to the Attribute class is probably a significant win for code bases with a lot of attrs classes, and can be trivially done by renaming the existing field _attributes to __slots__. This will be in the pull request too.)

Googling and playing around: the only way of making truly immutable classes in Python, I think, is by subclassing namedtuple. I'm not a huge fan of this approach though. My biggest philosophical objection is the fact that if this is done, isinstance(obj, tuple) and isinstance(obj, typing.Sequence) will be true. Instances of namedtuple subclasses are basically sequences/tuples. To me this is iffy.

Another approach is by disabling __setattr__, preferably combined with __slots__ so the __dict__ can't be modified directly. This isn't bulletproof, and __init__ basically depends on it not being bulletproof to set the initial values. The instances can still be changed by doing object.__setattr__(obj, 'name', val). If this is good enough, this approach is relatively straightforward.

What are your thoughts on this subject?

Here's my playground: https://github.com/Tinche/attrs/tree/feature/immutable-attributes

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions