[IronPython] __repr__ and __str__ for .NET types

Nicholas Bastin nbastin at opnet.com
Tue May 23 21:09:55 CEST 2006


On May 23, 2006, at 2:58 PM, Jonathan Jacobs wrote:

> Nicholas Bastin wrote:
>> No, actually it doesn't.  The string returned by __repr__ should be
>> able to be used to re-create the object, if that is possible.  In
>> this case,  'X: 0\nY: 0\nZ: 0\n' is a *lot* closer to re-creating the
>> object than  '<Foo object at 0x000000000000002B>' is.  The second
>> case is what gets returned when it isn't possible to re-create the
>> object, but that obviously isn't the case in the example of
>> DirectX.Vector3.
>
> Well, according to the documentation it should look like a valid  
> Python
> expression (which "X: 0\nY: 0\nZ: 0\n" does not) and if that isn't  
> possible
> then it should be in the form of "<...useful information...>".

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.

Although, lets be clear in this case, I have no idea whether either  
one of those constructions will actually work for the object in  
question (well, clearly the eval() construction won't work).  It's  
just that it's much more common to find a __repr__ which makes the  
first construction valid more often than the second.  (Obvious,  
<Object foo at 0xFFFFFFFF> isn't going to solve anybody's problem  
when it comes to recreating the object).

--
Nick




More information about the Ironpython-users mailing list