binding a reference to a variable

Tim Peters tim.one at comcast.net
Wed Apr 10 19:38:28 EDT 2002


[Andrew Koenig]
> Sure.  I'm thinking about how to implement Snobol-style pattern
> matching in Python.  I know that someone has done it before, but
> I want to approach it from a completely different direction.

I did that a looong time ago, but the code didn't survive my then-employer's
financial meltdown.  Unless you bought their assets at the fire sale, I'm
not sure how you could know whether your approach is completely different
<wink>.

It is, though.  The use of unevaluated expressions in SNOBOL4 is crucial for
advanced matching, and the "how do you do that with a bare name in Python?"
problem seems unsolvable in a squeaky clean way.  Like:

    ARB = NULL | LEN(1) *ARB

I ended up with something like

    import S

    arb = S.var('arb')
    arb.set(S.null | (S.len(1) + arb))

I could get *used* to the subtleties (since the Python binding for arb never
changes, cross- and self- references in the pattern-graph structures comes
for free), but fiddle it as I might, it never felt wholly natural.

> ...
> Focusing just on the  (break("@") . id)  subexpression, how would
> one implement it?  That's what led me on this path.

After I left that path <wink>, I found it was much easier to model Icon's
spelling of patterns, and with generators in 2.2 that can be a breeze.
However, Icon pattern-matching has a more procedural flavor, and SNOBOL4
pattern-matching a more declarative flavor, and each has strengths and
weaknesses following from that.

Before I left that path, it looked something like

    id = S.var('id')
    ... id.ass(S.break('@')) ...

were .ass() had an optional argument to choose between delayed (.) and
immediate ($) assignment, defaulting to delayed.  BTW, operator overloading
was much harder to predict in Python back then, so I often settled for
ordinary method-call notation.  After operator overloading because easy to
predict in Python, I learned to hate it from being forced to endure reading
code that used it <0.7 wink>.

An iteration before that I used string names as keys to an explicit
namespace dictionary (as others have suggesting), but found that modeling
"SNOBOL4 variable" as a class in its own right felt at least a little
better, despite needing explicit "declarations", i.e. lines of the form

    var1, var2, ... = S.var(name1, name2, ...)

Remembering to do that once was less painful than needing to slop in quotes
everywhere.

Have fun!  It's an interesting challenge.






More information about the Python-list mailing list