[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Question about implementing immutability

Dan Sommers <2QdxY4RzWzUUiLuE at potatochowder.com> wrote:
> If an instance of your class contains a list, and you change one
> of the elements of that list, then the instance's __setattr__
> never comes into play:

I think that's within the bounds of what is understood as
"immutable" in Python. Tuples possesses that same property:
you can modify members of the tuple (if mutable), but not
the tuple itself.:

    >>> t = (1, [])
    >>> t[1].append(2)
    >>> t
    (1, [2])

dieter <dieter at handshake.de> wrote:
> Most instances of classes store their attributes in the
> so called "instance dict", accessed via "<i>.__dict__".
> Thus, usually, it is quite easy to avoid `__setattr__":
> just modify the instance dict directly.

I don't think that's a problem. I'm willing to consider
direct __dict__ access as "breaking the rules" on the part
of the user.

> The instrumentation would ensure that the initial "__init__" call
> sets an instance attribute (say) "_initializing_" (to itself)
> (using implementation details) at its beginning and remove it at the end.
> This way, a "__setattr__" has an easy way to recognize the initialization
> phase. The approach above, would not work for recursively called
> "__init__" methods - but hopefully, such "__init__" implementations
> are extremely rare.

Instrumentation seems more tricky, but I didn't think
of this edge-case. Thank you for pointing this out.

Iwo Herka