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

Sven Marnach sven at marnach.net
Wed Apr 18 14:55:15 CEST 2012

Max Moroz schrieb am Wed, 18. Apr 2012, um 02:57:37 -0700:
> I'm really just trying to get a guarantee from the language that would
> make my original code safe. As is, it relies on a very reasonable, but
> undocumented, assumption about the behavior of built-in classes'
> __new__ method

Simon's point is that your current code *is* safe since your instances
are not immutable.

> The exact guarantee I need is: "Any built-in class' __new__ method
> called with the cls argument set to a user-defined subclass, will
> always return a new instance of type cls."

As long as your class does not set `__slots__` to an empty sequence,
you already have this guarantee, since your type is not immutable.
And while the current documentation might suggest that built-in types
would be allowed to check for empty `__slots__` and reuse already
created instances of a subclass in that case, it's very unlikely they
will ever implement such a mechanism.

So just don't define `__slots__` if you want this kind of guarantee,
or better even, add an ID to your instances to make the differences
you rely on explicit.


More information about the Python-ideas mailing list