Macros in python (PEP 638)



python中一个更新的宏PEP是:https://www.python.org/dev/peps/pep-0638/.使用它,是否可以定义如下宏:

PRINT = print ("Move from %s to %s." % (FROM, TO))

或者:

#define PRINT print ("Move from %s to %s." % (FROM, TO))

(或任何语法(。如果是这样的话,怎么能做到呢?

这里有一个非常、非常、非常基本的例子,说明如何使用宏进行基本的零参数文本替换。对于任何更严重/非琐碎的事情,都可以使用许多其他工具,例如C的预处理器:

# pypp.py
assert len(argv) == 3
# USAGE: $ python pypp.py script.py
# Does not allow arguments
# does not check whether it's in a string/comment.
# Very crude/basic, but but can be used for simple string-replacements
# such as the OP question.
from sys import argv
import re
with open(argv[-1], 'r') as f:
program = f.read()
matches = re.findall(r's*#s*define (S+) (.+?)(?<!\)n', program)
for match in matches:
program = (program
.replace(match[0], '###', 1) # ignore first occurrence (macro itself)
.replace(match[0], match[1])
)
exec(program)

最新更新