generic object - moving toward PEP

Paul McGuire ptmcg at austin.rr._bogus_.com
Sun Nov 21 16:56:18 EST 2004


"Steven Bethard" <steven.bethard at gmail.com> wrote in message
news:aJtnd.118100$HA.81413 at attbi_s01...
<snip>
> (3) Allows simple conversion from dict-style access to attribute access:
>
>  >>> d = {'a':2, 'b':4, 'c':16, 'd':256}
>  >>> d['a'], d['d']
> (2, 256)
>  >>> b = bunch(**d)
>  >>> b.a, b.d
> (2, 256)
>
> This could actually be supported recursively, if that seems useful:
>
>  >>> d = {'a':2, 'b':4, 'c':{'d':16, 'e':256}}
>  >>> b = bunch.frommapping(d)
>  >>> b.c.d
> 16

Steven -

This sounds *very* much like the ParseResults class that I implemented in
pyparsing.  For a given set of results from a parsing operation, one can
access them:
- as a list (tokens[0], tokens[1], ...)
- as a dict (tokens["name"], tokens["phoneNum"], ...)
- as attributes (tokens.name, tokens.phoneNum, ...)

I started out just returning lists of tokens, but found that it was
important to support some level of naming to the returned tokens -
otherwise, maintenance in the face of modifying grammars became very
difficult.  For example, if an optional token were inserted between name and
phoneNum, now one would need to do a lot of testing on number and types of
returned tokens - very messy!  Instead, the tokens are given names as
defined in the grammar specification, so that intervening syntax doesn't
mess things up.

Then, I added the attributes-style access because it looks more Pythonic.

ParseResults can also be accessed recursively.  If phoneNum were defined
with sub-fields, one could access tokens.phoneNum.areaCode or
tokens["phoneNum"]["areaCode"], for example.

As an afterthought, I then added an XML output format for this class, so
that tokens.asXML("PERSONAL_DATA") would generate:
<PERSONAL_DATA>
  <name>John Doe</name>
  <phoneNum>555-1212</phoneNum>
</PERSONAL_DATA>

ParseResults defines quite a number of operators for managing and
manipulating ParseResults objects.  I think this class may give you some
ideas about your bunch class.  I guess some of the code may appear kludgey,
such as the __new__ handling, but it seems to be holding up reasonably well.

HTH,
-- Paul





More information about the Python-list mailing list