fun codeop hack
logistix
logstx at bellatlantic.net
Tue Mar 12 22:05:02 EST 2002
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
More information about the Python-list
mailing list