Velocity Reviews > Recursive Str?

# Recursive Str?

Chris S.
Guest
Posts: n/a

 10-22-2004
Why do most, if not all, compound Python structures not convert their
elements to strings recursively?

>>> class foo:

.... def __init__(self, a):
.... self.a = a
.... def __str__(self):
.... return 'foo('+str(self.a)+')'
....
>>> from sets import Set
>>> a=Set([foo(1)])
>>> print a

Set([<__main__.foo instance at 0x01C01968>])
>>> def SetStr(self):

.... text = []
.... for n in self:
.... text.append(str(n))
.... return 'Set('+', '.join(text)+')'
....
>>> Set.__str__ = SetStr
>>> print a

Set(foo(1))

Steven Bethard
Guest
Posts: n/a

 10-22-2004
Chris S. <chrisks <at> NOSPAM.udel.edu> writes:

>
> Why do most, if not all, compound Python structures not convert their
> elements to strings recursively?
>
> >>> class foo:

> ... def __init__(self, a):
> ... self.a = a
> ... def __str__(self):
> ... return 'foo('+str(self.a)+')'
> ...
> >>> from sets import Set
> >>> a=Set([foo(1)])
> >>> print a

> Set([<__main__.foo instance at 0x01C01968>])

Well, they call the __repr__ method, not the __str__ method:

>>> class foo:

.... def __init__(self, a):
.... self.a = a
.... def __str__(self):
.... return 'foo(%s)' % self.a
....
>>> set([foo(1)])

set([<__main__.foo instance at 0x009D8030>])
>>> class foo:

.... def __init__(self, a):
.... self.a = a
.... def __repr__(self):
.... return 'foo(%s)' % self.a
....
>>> set([foo(1)])

set([foo(1)])

Were you just looking for this behavior, or were you asking why it's __repr__
and not __str__?

Steve

Chris S.
Guest
Posts: n/a

 10-22-2004
Steven Bethard wrote:

> Were you just looking for this behavior, or were you asking why it's __repr__
> and not __str__?
>
> Steve

Actually, it seems I'm confusing __str__ with __repr__. Now things make
sense. Thanks for the clarification.

Steven Bethard
Guest
Posts: n/a

 10-22-2004
Chris S. <chrisks <at> NOSPAM.udel.edu> writes:
>
> Actually, it seems I'm confusing __str__ with __repr__. Now things make
> sense. Thanks for the clarification.

You're welcome. Glad it was the easy question, not the hard one -- I never
did bother to look up the __repr__ vs. __str__ discussions on this topic.

Steve