[IronPython] __repr__ and __str__ for .NET types

Neville Bagnall neville.bagnall at propylon.com
Wed May 24 15:45:24 CEST 2006


>> Generally we try to meet in the middle on __repr__ - in many cases,  
>> it's most convenient if the output from __repr__ can be fed back into a  
>> factory or constructor for the class the text came from, so that the  
>> following expression is legal:
>>  new_object = Microsoft.DirectX.Vector3(repr(old_object))
>>  since
>>  eval(repr(old_object))
>>  usually isn't convenient, fast, or safe.
>Consider the output of repr(file('foo', 'rw')).

The standard library is inconsistent on this, some return "< description  
>", some an evaluable expression, (e.g. sets,mhlib).

The docs say:

'If at all possible, this should look like a valid Python expression that  
could be used to recreate an object with the same value (given an  
appropriate environment). If this is not possible, a string of the form  
"<...some useful description...>" should be returned.'

My reading of that, and the example of the standard library, suggests that  
repr(Microsoft.DirectX.Vector3()) should return something like  
"Vector3(0,0,0)".

But I don't see how IronPython can produce valid recreation expressions in  
the general case. Given that, my reading of the docs is that the angle  
delimiters are the conventional method of distinguishing descriptive repr  
strings from valid expressions.

FWIW in the general case I would have something equivalent to:

def GenRepr(object):
     strrep=object.ToString()
     if len(strrep)<40 and strrep.find('\n')==-1:
         return "<%s: %s>" % (object.__class__.__name__, repr(strrep)[1:-1])
     else:
         return "<%s at 0x%x>" % (object.__class__.__name__, id(object))

i.e. include a string representation only where it is reasonably concise,  
and include the markers in both cases.

Neville.



More information about the Ironpython-users mailing list