fun codeop hack

Cromwell, Jeremy jcromwell at ciena.com
Thu Mar 14 13:52:50 EST 2002


This is fun.  For simplicity, also add this routine to codeop.py:
def addMacro(pattern, result):
    import re
    patRe = re.compile(pattern)
    def _macro(string):
        return patRe.sub(result, string)
    Compile.macros.append(_macro)

Now you can do this:
>>> import codeop
>>> codeop.addMacro(r'for\s+(\w+)\s*=\s*(\d+)\s+to\s+(\d+)\s*:', r'for \1 in
range(\2, 1 + \3):')
>>> for i = 1 to 6:
... 	print i
... 	
1
2
3
4
5
6
--Jeremy Cromwell


-----Original Message-----
From: logistix [mailto:logstx at bellatlantic.net]
Sent: Tuesday, March 12, 2002 7:05 PM
To: python-list at python.org
Subject: fun codeop hack


Replace the Compile class with the following:

class Compile:
    """Instances of this class behave much like the built-in compile
    function, but if one is used to compile text containing a future
    statement, it "remembers" and compiles all subsequent program texts
    with the statement in force."""
    macros = []
    def __init__(self):
        self.flags = 0

    def __call__(self, source, filename, symbol):
        for macro in Compile.macros:
            source = macro(source)
        codeob = compile(source, filename, symbol, self.flags, 1)
        for feature in _features:
            if codeob.co_flags & feature.compiler_flag:
                self.flags |= feature.compiler_flag
        return codeob

============================
Now you can do all kinds of fun stuff like this
in IDLE and PythonWin
============================
PythonWin 2.2 (#28, Dec 21 2001, 12:21:22) [MSC 32 bit (Intel)] on win32.
Portions Copyright 1994-2001 Mark Hammond (mhammond at skippinet.com.au) - see
'Help/About PythonWin' for further copyright information.
>>> import re
>>> forRe = re.compile(r'for\s+(\w+)\s*=\s*(\d+)\s+to\s+(\d+)\s*:')
>>> def newFor(string):
...  return forRe.sub(r'for \1 in range(\2, 1 + \3):',string)
...
>>> import codeop
>>> codeop.Compile.macros.append(newFor)
>>>
>>> for i = 1 to 6:
...  print i, i*i
...
1 1
2 4
3 9
4 16
5 25
6 36
>>>

PS. For the record I'm perfectly happy with current for loop syntax.  Just
thought it was a good example



-- 
http://mail.python.org/mailman/listinfo/python-list




More information about the Python-list mailing list