Reaching subtrees

Tim Peters tim_one at email.msn.com
Sat Sep 18 13:58:48 EDT 1999


[François Pinard]
> Wow!  Re-wow!  Look:
>
> >>> for (a, (b, c)) in [(1, ((2, 3), (4, 5))), ((11, 12), (13, 14))]:
> ...	print a, b, c
> ...
> 1 (2, 3) (4, 5)
> (11, 12) 13 14
> >>> def x(a, (b, c)):
> ...	print a, b, c
> ...
> >>> x(1, ((2, 3), (4, 5)))
> 1 (2, 3) (4, 5)
> >>> x((11, 12), (13, 14))
> (11, 12) 13 14
>
> So, if I understand and believe what I see, it might be quite easy in
> Python to reach precise subtrees of trees, given that skeletons match?

Right.

> This, combined with `try:' statements, I guess one could fastly
> see is some tree matches a fixed skeleton, and then rebuild it
> differently if it does.

Hmm!  It's certainly been used to pull apart simple tree structures and
rearrange them, but I'm not sure I've seen it so used except when the
structure was known in advance.  If you have, say, 2**N possible tree
structures in mind, a linear sequence of 2**N try/except blocks isn't likely
to be "fast" <wink>.  I suppose a hierarchical approach could be made to
work quickly, though, like

    if len(x) == 2:
        left, right = x
        if len(left) == 2:
            l1, l2 = left
            ...
        elif ...:
            ...
    elif ...:
        ...

But that kind of code is pretty obscure!

> Is this fully documented, and meant to be a dependable part of
> the language?

Yes * 2.  See section 6.3 ("Assignment statements") of the language (not
library) reference manual.

> This feature pushes Python forward for elegant writing for simple,
> modest, fixed transformational grammars ...
> Would someone know any Python work in that direction which I could
> admire, then shamelessly use for inspiration? :-)

The most interesting work is at the other end of the spectrum:  general
context-free grammars and arbitrary transformations of parse trees.  John
Aycock has written an elegant framework for this (use python.org's search,
or DejaNews).  It's built on an all-purpose Earley parser, and in the latest
version plays a cool trick in the tree transformation phase, using the
Earley parser again to "parse" the structure of the parse trees themselves.
Wonderfully generally, delightfully quick to whip up a little compiler, and
astonishingly slow <0.9 wink>.

I (although John does not) often use Python's argument-list unpacking
feature when using John's system, but in that case class methods are
associated with specific productions, and each production in general fully
determines the top one or two levels of the partial parse tree its
associated method will see.  So unpacking is not used as a pattern-matching
gimmick here, it's just handy to unpack a structure whose form is known in
advance.  The latter is what it was designed for, of course!  Trying to use
it for more than that will probably get clumsy.

which-is-just-guido's-way-of-frowning-at-you<wink>-ly y'rs  - tim






More information about the Python-list mailing list