Making immutable instances

Mike Meyer mwm at mired.org
Wed Nov 30 01:18:22 EST 2005


Paul Rubin <http://phr.cx@NOSPAM.invalid> writes:
> Mike Meyer <mwm at mired.org> writes:
>> When it was suggested that a facility for doing this be added to the
>> language, I asked for a use case for it. Nobodies come up with a
>> reason for placing such restriction on the client yet. If you've got a
>> use case, I'd be interested in hearing it.
> I see it the other way; almost all the time in my own code I try to
> initialize all of any instance's attributes in an __init__ method.
> Dynamically adding attributes is useful sometimes, but done
> willy-nilly leads to spaghetti code.

Pretty much anything, if abused, can lead to "spaghetti code".

> In the cases where it's useful,
> I'd rather see it done through a special __setattr__ method, perhaps
> inherited from a mixin:
>
>   class Frob(Whatsit, DynamicAttributeMixin):
>      ...
>
> However, that's not likely to happen.

The thing is, the need for an extra attribute doesn't come from your
class, it comes from the client of your class. You can't know if the
client code will need that facility or not, so the only choice you
know won't be wrong sometime is to always add the mixin. In which
case, you should follow the Python "the less boilerplate, the better"
practice, and leave it off. Which is what we have.

Letting the class author declare whether or not the client can add
attributes is wrong for the same reasons - and in the same places -
that letting the class author declare that the client shouldn't be
allowed to access specific attributes, and so on, is wrong.  Of
course, it's also *right* for the same reasons and in the same places
as those things. I just don't think those places happen in Python
programs.

       <mike
-- 
Mike Meyer <mwm at mired.org>			http://www.mired.org/home/mwm/
Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information.



More information about the Python-list mailing list