eval(repr(x)) == x

Oren Tirosh oren-py-l at hishome.net
Sun Jan 27 10:07:33 EST 2002


On Sun, Jan 27, 2002 at 11:14:47AM +0000, Alex Martelli wrote:
> Oren Tirosh wrote:
> 
> > For many python builtins eval(repr(x)) == x.  I find this property very
> > useful for debugging and writing tests.  In some cases I write my own
> > classes so their repr is an expression that recreates their state.
> 
> It's sort of nice when it works, but I don't quite see how this translates
> into "very useful for debugging and writing tests".  Examples please?

A unit test often consists of a sequence of method calls and their expected
results.  Writing these expected results is a pain in the a**. A relatively
easy way to generate the expected result is to construct it in an 
interactive session, print it and then select and paste to the test code. 
But this depends on eval(repr(x))==x.

> I would find it somewhat of a problem not being able to tell from repr(x) 
> whether x is a function, a submodule of a package, a class, etc.  I think
> it's more important for repr(x) to identify x reasonably well (compatibly
> with not taking up a thousand characters:-) rather than striving for repr
> to be eval's inverse -- which it can be only up to a point (e.g. the above
> repr only works after

It may be possible to get both at the same time. The repr function doesn't
have to do all the work by itself.  The displayhook can help by printing

    "<%s> %s" % (repr(type(_)), repr(_)) 

unless _ is of a type like int, list, etc that already has a valid
expression as its repr. In that case it's enough to just print repr(_).

>>>'spam'
'spam'		# not "<str> 'spam'"
>>>int
<type> int
>>>type
<type> type
>>>repr
<builtin_function_or_method> repr
>>>sys
<module> sys
>>>sys.exit
<builtin_function_or_method> sys.exit
>>>class A: pass
>>>A
<class> __main__.A
>>>A()
<__main__.A> instance at 0xADDRESS

   no-I-don't-think-repr-is-a-replacement-for-pickle-ly yours,

	Oren





More information about the Python-list mailing list