repr(x) == repr(y) <=> x == y AND eval(repr(x)) == x

Chris Liechti cliechti at gmx.net
Fri Oct 18 15:55:59 EDT 2002


Thorsten Kampe <thorsten at thorstenkampe.de> wrote in news:aopma6$odeho$1 at ID-
77524.news.dfncis.de:

> Hi,
> 
> I'm using dictionaries for some "very generalized programs". This
> means that I cannot tell in advance if all the items I'm operating on
> are hashable. The "trick" that came to my mind was to use repr(x) as
> the key (instead of x).
> 
> This relies on two assumptions:
> 
> 1. repr(x) == repr(y) <=> x == y
> 
> 2. eval(repr(x)) == x (for further processing)
> 
> A wise man once said to me:
> ,---
>| You're FAR more likely to meet objects where you can't count on
>| eval(repr(x)) == x, than non-hashable objects.
> `---
> 
> Does anyone know under which circumstances 1. and 2. are wrong?

1)
>>> class A:
... 	def __init__(self, v):
... 		self.v = v
... 	def __cmp__(self, other):
... 		return cmp(self.v, other.v)
... 
>>> a = A(7)
>>> b = A(7)
>>> a
<__main__.A instance at 0x010F6970>
>>> b
<__main__.A instance at 0x010F4D08>
>>> a==b
1
>>> repr(a) == repr(b)
0

2) many user object either use repr in a custom way / not emmiting python 
syntax or they don't define __repr__ at all (see 1 for such an example)

what you should do is to use the pickle module to convert instances to 
strings and back.

chris

-- 
Chris <cliechti at gmx.net>




More information about the Python-list mailing list