Formatted printing of deep tuples
Ignacio Vazquez-Abrams
ignacio at openservices.net
Fri Oct 5 04:11:07 EDT 2001
On Fri, 5 Oct 2001, Richard Jones wrote:
> Bored. Wrote this:
Heh. I write some of my best code when bored.
> def format_tuple(out, tuple, indent=''):
> out('%s(\n'%indent)
> new_indent = indent+' '
> for element in tuple:
> if type(element) == type(()):
> format_tuple(out, element, new_indent)
> else:
> out('%s%r,\n'%(new_indent, element))
> out('%s)\n'%indent)
>
> import sys
> out = sys.stdout.write
> format_tuple(out, (((1, 2),), ((), ('a', (('b', 'c'),)))))
>
>
> Might write another before I go home ;)
Already done. Take a look at this:
---
def format_tuple(input, indent=2, _indent=0, chars='()', first=0):
ret='%s%s' % (_indent*' ', chars[0])
for element in range(len(input)):
if element:
ret=ret+', '
if type(input[element])==type(()):
ret=ret+'\n'+format_tuple(input[element], indent, _indent+indent, '()', 0)
first=1
elif type(input[element])==type([]):
ret=ret+'\n'+format_tuple(input[element], indent, _indent+indent, '[]', 0)
first=1
else:
ret=ret+'%s' % (`input[element]`)
first=0
ret=ret+'%s%s%s' % (first*'\n', first*_indent*' ', chars[1])
return ret
print format_tuple((((1, 2),), ((), ('a', (['b', 'c'],)))))
---
I made the ouput a little clearer than my initial spec (like that's a _bad_
thing...).
--
Ignacio Vazquez-Abrams <ignacio at openservices.net>
More information about the Python-list
mailing list