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

Sven Marnach sven at marnach.net
Thu Apr 19 12:35:13 CEST 2012


Steven D'Aprano schrieb am Wed, 18. Apr 2012, um 23:22:55 +1000:
> 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.

This was also my first reaction; there is one case, though, which you
wouldn't need a cache for:  if the constructor is called with an
instance of the subclass as an argument.  As an example, the tuple
implementation does not have a cache of instances, and reuses only
tuples that are directly passed to the constructor:

    >>> a = 1, 2
    >>> b = 1, 2
    >>> a is b
    False
    >>> b = tuple(a)
    >>> a is b
    True

It wouldn't be completely unthinkable that a Python implementation
chooses to extend this behaviour to immutable subclasses of immutable
types.  I don't think there is any reason to disallow such an
implementation either.

Cheers,
    Sven



More information about the Python-ideas mailing list