is there a simple way to abuse parser for this?

Alexander Schmolck a.schmolck at gmx.net
Fri Oct 1 19:14:32 CEST 2004


I sometimes find myself in the situation that I want to perform some simple
source code changes, queries etc. in the code regions of a python file (i.e.
outside comments and strings).

I thought a reasonable way to achieve this might be to have some simple minded
regexp that does the job but doesn't pay attention to strings (or comments,
but those would usually be relatively easy to handle) and then only check
*after* a match was found whether this match occured in a valid region (since
false positives should be rare).

i.e.:

    def replaceStuff(match):
        if validRegion(match.start, match.end):
           ...
        else:
           return match.group(0)
    ...  
    re.sub(regexp, replaceStuff, pythonFile)


I was wondering whether python's parsing services (which I haven't used so
far) could be easily coopted for the ``validRegion`` detection (one could of
course use a regexp to find string and comment boundaries but that has the
disadvantage that it's lest robust, e.g. it might break if new syntax is
introduced).


'as



More information about the Python-list mailing list