unittest.py: what is TestResult.__repr__ ?

Joshua Macy l0819m0v0smfm001 at sneakemail.com
Fri Mar 15 15:49:57 EST 2002


Richard Harlos wrote:

> I'm not a Python programmer (at least, not yet ;)
> 
> I am, however, trying to port the unittest.py framework to another
> language.  Of all the languages that this testing framework has been
> ported to, I thought that Python would be the easiest for me to
> decipher.  For the most part, it seems pretty straightforward, except
> for...
> 
> I'm presently stuck in the TestResult class.  Though I've searched for
> the meaning of "__repr__" in the Python22 documentation, I cannot find
> it.
> 
> Please help me understand this this convention of using leading and/or
> trailing underscores in Python.
> 
> Thanks in advance...
> 
> Richard
> 

Check the documentation under special method names: 
http://www.python.org/doc/current/ref/specialnames.html

Basically, any method name that both begins and ends with a 
double-underscore is a way for your own class to define behavior that 
happens when certain syntax is used, e.g. if you define an __add__ 
method, that method is called when an object of your class is discovered 
to the left of a + sign in an expression.

The __repr__ special method is used to define a string representation of 
the object; it is called when someone invokes repr() on your object, or 
by backticks, e.g. `myObj`, or when you type the object name and nothing 
else at the interactive prompt.  It's supposed to return a string that 
can be eval-ed to recreate the object (if possible) or a simple 
description like '<function f at 0x813dd>'
E.g.

 >>> class Test:
...   def __init__(self, value):
...       self.value = value
...   def __repr__(self):
...       return 'Test(%s)' % self.value
...
 >>> t = Test(1)
 >>> t
Test(1)
 >>> repr(t)
'Test(1)'
 >>> `t`
'Test(1)'
 >>> t2 = eval(repr(t))
 >>> t2
Test(1)

   Hope this helps,

   Joshua







More information about the Python-list mailing list