[IronPython] __repr__ and __str__ for .NET types

Jonathan Jacobs korpse-ironpython at kaydash.za.net
Tue May 23 22:50:35 CEST 2006


Nicholas Bastin wrote:
> 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')).

> 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,  

I'm not aware of any .NET objects that can be constructed by a single string 
containing newline-separated variables / value pairs and leave you with 
something useful (apart from string and like circumstances, obviously.)

> <Object foo at 0xFFFFFFFF> isn't going to solve anybody's problem  
> when it comes to recreating the object).

No, but __repr__ is supposedly for debugging; it's quite difficult to tell the 
difference between vector A with X = Y = Z = 0 and vector B with X = Y = Z = 0 
with just the current output. There is also the case where ToString returns 2 
pages of variable / value pairs. If I want to see variable / value pairs I'm 
quite capable of using repr(obj.__dict__).
-- 
Jonathan




More information about the Ironpython-users mailing list