[Python-ideas] Providing a guarantee that instances of user-defined classes have distinct identities

Mike Meyer mwm at mired.org
Wed Apr 18 15:19:17 CEST 2012

On Wed, 18 Apr 2012 11:44:47 +1000
Nick Coghlan <ncoghlan at gmail.com> wrote:

> On Wed, Apr 18, 2012 at 11:23 AM, Max Moroz <maxmoroz at gmail.com> wrote:
> > "For immutable types, operations that compute new values may actually return
> > a reference to any existing object with the same type and value, while for
> > mutable objects this is not allowed."
> >
> > Nowhere in the documentation is it clearly defined which objects are
> > considered "immutable" for the purpose of this promise. As a result, a
> > Python implementation, now or in the future, may decide that it's ok to
> > return a reference to an existing object when a Card instance is created -
> > since arguably, class Card is immutable (since it derives from an immutable
> > base class, and doesn't add any new attributes).
> It's up to the objects themselves (and their metaclasses) - any such
> optimisation must be implemented in cls.__new__ or metacls.__call__.

First, the Python docs don't clearly tell you what objects are
immutable because, well, it's an extensible language. With that
constraint, the best you can do about that is what it says not far
above the section you quoted:

      An object’s mutability is determined by its type; for instance,
      numbers, strings and tuples are immutable, while dictionaries
      and lists are mutable.

I.e. - that this is determined by it's type, and a list of builtin
types that are immutable.

> So, no, you're not going to get a stronger guarantee than is already
> in place

I believe that this guarantee is strong enough to guarantee that
classes that inherit from immutable types won't share values unless
the class code does something to make that happen. The type of such an
object is *not* the type that it inherits from, it's a Python class
type. As demonstrated, such classes aren't immutable, so Python needs
to make different instances different objects even if they share the
same value. If you want behavior different from that, the class or
metaclass has to provide it.

Mike Meyer <mwm at mired.org>		http://www.mired.org/
Independent Software developer/SCM consultant, email for more information.

O< ascii ribbon campaign - stop html mail - www.asciiribbon.org

More information about the Python-ideas mailing list