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

Nick Coghlan ncoghlan at gmail.com
Wed Apr 18 03:44:47 CEST 2012


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__.

So, no, you're not going to get a stronger guarantee than is already
in place (and you'd be better of just writing Card properly -
inheriting from int for an object that should model a "value, suit"
2-tuple is a bad idea. Using collections.namedtuple would be a much
better option.

Cheers,
Nick.

-- 
Nick Coghlan   |   ncoghlan at gmail.com   |   Brisbane, Australia



More information about the Python-ideas mailing list