Making immutable instances

Alex Martelli aleax at mail.comcast.net
Thu Nov 24 18:23:11 CET 2005


Ben Finney <bignose+hates-spam at benfinney.id.au> wrote:
   ...
> > A type implemented in C offers different possibilities than one
> > implemented in Python -- no deep conceptual reason, just practical
> > ones.
> 
> So, in the hypothetical situation that all Python types were
> implemented in pure Python, what would the ideal behaviour for
> immutables be? Or would there be no immutables?

Pypy is implementing Python in Python and using just the same semantics
as CPython.  Of course, there IS some sleight of hand, because there are
still two "sides" -- interpreter level and application level... stuff
implemented in interpreter level Python plays just the same role as
stuff implemented in C does in CPython.

Musing theoretically, I can see an *ideal* approach would have to meet
higher aesthetic goals than Python's -- reach for richer symmetry, e.g.,
all types existing in mutable and immutable flavors (Ruby comes sort of
close, with plain and frozen objects).  Python's more about pragmaticity
than purity (and, therefore, than idealness)...


> I'm looking for a "consenting adults" restriction: classes will have
> immutable instances only where it makes sense from the class protocol.
> I'm not going to lose sleep over users who go looking for trouble.

Yep, I understand this, now that you've explained in more detail, and
FWIW I do approve.

One more piece of advice: you might document that, in circumstances
where (using a normal Python class's instances) the obvious approach
would be to add some per-instance attribute to the instances (with
semantics totally outside the class), your users might be better advised
to employ a weakref.WeakKeyDictionary with the instances as keys.
Although a tad more cumbersome, they can get the same semantics this
way, even though it may seem "inside-out" wrt the "intuitive" approach.


Alex



More information about the Python-list mailing list