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

Steven D'Aprano steve at pearwood.info
Wed Apr 18 15:22:55 CEST 2012

Max Moroz wrote:

> 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
> 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."
> (Emphasis on "new instance" - as opposed to a reference to an existing object.)

I can't help feel that you are worrying about nothing. Why would a built-in 
class ever return an existing instance of a sub-class? While technically it 
would be possible, it would require the built-in class to keep a cache of 
instances for each subclass. Who is going to do that, and why would they bother?

It seems to me that you're asking for a guarantee like:

"Calling len() on a list will never randomly shuffle the list as a side-effect."

The fact that len() doesn't shuffle the list as a side-effect is not a 
documented promise of the language. But does it have to be? Some things would 
be just stupid for any implementation to do. There is no limit to the number 
of stupid things an implementation might do, and for the language to specify 
that it doesn't do any of them is impossible.

I think that __new__ returning an existing instance of a subclass would be one 
of those stupid things. After all, it is a *constructor*, it is supposed to 
construct a new instance, if it doesn't do so in the case of being called with 
a subclass argument it isn't living up to the implied contract.

I guess what this comes down to is that I'm quite satisfied with the implied 
promise that constructors will construct new instances and don't think it is 
necessary to make that explicit. It's not that I object to your request as 
that I think it's unnecessary.


More information about the Python-ideas mailing list