[Python-Dev] Re: redefining is

Andrew Koenig ark-mlist at att.net
Fri Mar 19 15:55:44 EST 2004


> Equivalency at this point in time is different from being equivalent at
> all points in time in the future.

If you like.

> Equivalent now, is something we can test easily with the current '=='.

Not really, at least not in the presence of user-define ==.

> Equivalent at all times in the future (what I would consider
> interchangeable) requires minimally testing object identities.  This
> seems to be going a bit beyond what 'is' is doing right now, as shown
> by:
> 
> >>> a = []
> >>> b = []
> >>> x1 = (a,b)
> >>> y1 = (a,b)
> >>> x1 is y1
> False
> 
> 'is' seems to be doing a shallow check of object identity (I may be
> wrong).

No, you're right.

> Testing whether or not two objects will be identical in the future would
> likely require a single-level id check along with being able to test
> whether an object is mutable or not.  For built-in structures (lists,
> tuples, dictionaries, strings...), this isn't so bad, we know what is
> immutable or not.  Seemingly a reasonable algorithm for determining
> whether two objects are interchangeable is as follows...
> 
> #list possibly not complete.
> _immutables = (int, str, float, tuple, type(None))

Certainly not complete, as it doen't include long or bool.

> immutables = dict([i, None for i in _immutables])
> def interchangeable(a,b):
>     if type(a) not in immutables or type(b) not in immutables:
>         return False
>     if type(a) is type(b) and type(a) is tuple:
>         #are immutable, but may contain objects whose
>         #identity may be important for the future
>         ia = map(id, a)
>         ib = map(id, b)
>         return ia == ib

That's not quite what I had in mind: You're testing for element identity
rather than interchangeability.  Perhaps something more like this:

		if len(a) != len(b):
			return False
		for x, y in zip(a, b):
			if !interchangeable(x, y):
				return False
		return True

>     #are immutable but aren't a container
>     return a == b

Also, this code does not take ImmutableSet into account.

> For user-defined classes, unless an interface is designed so that
> classes can say, "I am mutable" or "I am immutable", and there are ways
> to get their 'contents' (if such a thing makes sense), then testing
> potential interchangeability is a moot point, and is (currently)
> impossible.

Correct.  As things stand today, two distinct objects of user-defined
classes should never be considered interchangeable.





More information about the Python-Dev mailing list