Moving from Perl to Python

Tim Peters tim_one at email.msn.com
Sat Sep 25 23:01:02 EDT 1999


[Harry George, on converting Perl to Python]
> ...
> 2. Work out the regular expression tricks early -- I'm currently
>    looking for a python idiom for
>       s/@@([a-z]+)@@/$lookup{$1}/g
>
> Python needs a Cookbook.  Except for copyright issues, I'd say just
> redo all the Perl Cookbook examples in python -- or maybe O'Rielly has
> one in the works already.

Translation of that Perl into Python is straightforward but unsatisfying:

    import re
    lookup = { ... }
    pattern = re.compile(r"@@([a-z]+)@@")
    # s is input string, t is output string
    t = pattern.sub(lambda m: lookup.get(m.group(1), ""), s)

The point to using lookup.get with an empty-string default is to slavishly
mimic Perl's behavior of "erasing" the entire match string if lookup doesn't
contain the key.  I would much rather see an exception raised in that case,
and only partly because Python would prefer to raise one <wink>.

Over the long term, it's more fruitful to write Python from the start than
to mimic dubious Perl features.  For example, the data you're starting with
probably didn't come with @@xyz@@ thingies naturally, but that notation was
invented because someone knew it would be easy to substitute using Perl
s///g.  If the project started in Python, you'd be more likely to use
%(xyz)s notation in the data, so that substitutions could be done simply and
much more quickly via Python's

    t = s % lookup

idiom.  Regexps are not Python's forte, and all of speed, clarity and
maintainability will increase in proportion to your zeal in purging them.

so-ends-chapter-1-of-the-what-not-to-cook-book-ly y'rs  - tim






More information about the Python-list mailing list