How to pretty-print cyclic dictionaries?

Dietrich Bollmann diresu at web.de
Thu Apr 29 23:34:17 EDT 2010


Hi Robert,

On Thu, 2010-04-29 at 11:56 -0500, Robert Kern wrote:
> On 4/29/10 11:23 AM, Dietrich Bollmann wrote:
> > Hi,
> >
> > I would like to represent graphs as cyclic dictionaries in Python.
> >
> > The python code for the graphs is generated by some other program
> > (written in lisp) and I wonder what would be the best syntax for writing
> > the cycles in Python?
> 
> You can implement your ideas using Armin Ronacher's pretty.py:
> 
>    http://pypi.python.org/pypi/pretty
> 
> The default pretty printer for dicts looks like this:
> 
>      def dict_pprinter(obj, p, cycle):
>          if cycle:
>              return p.text('{...}')
>          p.begin_group(1, '{')
>          keys = obj.keys()
>          try:
>              keys.sort()
>          except Exception, e:
>              # Sometimes the keys don't sort.
>              pass
>          for idx, key in enumerate(keys):
>              if idx:
>                  p.text(',')
>                  p.breakable()
>              p.pretty(key)
>              p.text(': ')
>              p.pretty(obj[key])
>          p.end_group(1, '}')
> 
> You could conceivably subclass RepresentationPrinter (the variable p above is an 
> instance of this) that will assign increasing ID numbers to repeated objects so 
> you can tag them.

Thanks, this is what I was looking for!  ...But I would have to write a
parser also, so I'll first try Chris' and Garrick's yaml solution and if
I still find some time implement your approach later :)

Thanks for your help, Dietrich


> -- 
> Robert Kern
> 
> "I have come to believe that the whole world is an enigma, a harmless enigma
>   that is made terrible by our own mad attempt to interpret it as though it had
>   an underlying truth."
>    -- Umberto Eco

Maybe the mad and terrible part of the problem is Eco's definition of
'truth' ? :)

> 





More information about the Python-list mailing list