python中的宏(pep 638)

uxhixvfz  于 2021-07-13  发布在  Java
关注(0)|答案(1)|浏览(438)

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

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

或:

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

(或者不管什么语法)。如果是的话,那怎么办呢?

14ifxucb

14ifxucb1#

这是一个非常非常基本的例子,用宏来替换基本的零参数文本。对于任何更为严肃/重要的事情,还有许多其他工具可以使用,例如c的预处理器:

  1. # pypp.py
  2. assert len(argv) == 3
  3. # USAGE: $ python pypp.py script.py
  4. # Does not allow arguments
  5. # does not check whether it's in a string/comment.
  6. # Very crude/basic, but but can be used for simple string-replacements
  7. # such as the OP question.
  8. from sys import argv
  9. import re
  10. with open(argv[-1], 'r') as f:
  11. program = f.read()
  12. matches = re.findall(r'\s*\#\s*define (\S+) (.+?)(?<!\\)\n', program)
  13. for match in matches:
  14. program = (program
  15. .replace(match[0], '###', 1) # ignore first occurrence (macro itself)
  16. .replace(match[0], match[1])
  17. )
  18. exec(program)
展开查看全部

相关问题