2e46f5.org
「cpython-pep638: PEP 638 syntactic macros for Python, implemented in CPython 3.15.2」の 2e46f5.org です。「そのまま開く」はファイルをそのまま返します。
* cpython-pep638: PEP 638 syntactic macros for Python, implemented in CPython 3.15.2
:properties:
:export_file_name: generated/contents/blog/2026/2e46f5
:export_date: 2026-11-27 19:02
:export_updated: 2026-11-27 19:02
:export_lang: en
:export_original: /blog/2026/f4154e
:export_tags: python cpython pep macro ast compiler release cpython-pep638
:end:
[[https://peps.python.org/pep-0638/][PEP 638]] proposes syntactic macros for Python.
You write a macro in the form =name!=, and at compile time a function written in Python expands it and rewrites the AST.
I implemented this PEP in CPython 3.15.2.
I added rules to the parser and one layer that hands the AST to a Python function before compilation, and with those two changes macros run in CPython itself.
The repository is [[https://github.com/conao3/cpython-pep638][conao3/cpython-pep638]], and it stacks the implementation commits on the [[https://github.com/python/cpython/tree/v3.15.2][v3.15.2]] tag of python/cpython.
It derives from CPython, so it uses the same license, the PSF License Version 2, but it is my own experiment and has no connection to the CPython project.
[[github:conao3/cpython-pep638::Python][CPython 3.15.2 with PEP 638 syntactic macros]]
** Writing and using a macro
A macro processor is a Python function that you mark with a decorator from the =macros= module.
It receives the AST of the macro and returns the AST that replaces it.
#+begin_src python
# mymacros.py
import ast
import macros
@macros.macro_processor(macros.STMT_MACRO, 1, "finally")
def try_(node, finally_):
return ast.Try(body=node.body, handlers=[], orelse=[],
finalbody=finally_.body)
@macros.macro_processor(macros.EXPR_MACRO, 1)
def quote(node):
return ast.Constant(ast.unparse(node.args[0]))
#+end_src
=try_= is a statement macro that takes the =finally!:= clause after it as its second argument, and =quote= is an expression macro that turns its argument expression into a source string.
In the code that uses the macros, =from!= imports the processors.
#+begin_src python
# main.py
from! mymacros import try_
from! mymacros import quote
def read(log):
try_!:
return quote!(a + b * c)
finally!:
log.append("closed")
log = []
print(read(log), log)
#+end_src
I run this with the =python= built from this repository.
#+begin_src console
$ ./python main.py
a + b * c ['closed']
#+end_src
=quote!(a + b * c)= became the string ='a + b * c'=, and =try_!= became a =try= statement with a =finally= clause.
Neither =a= nor =b= is defined, but the macro replaces the expression with a string before Python can evaluate it, so you get no error.
** Macro syntax
A macro name is an identifier followed by =!= with no space between them, and a keyword followed by =!=, such as =from!= or =finally!=, is also a macro name.
[[https://peps.python.org/pep-0638/#statement-form][Statement macros]] take this form.
#+begin_src text
name! [引数] [import NAME] [as NAME] [: ブロック]
#+end_src
An expression macro takes the form =name!(引数)=, but [[https://peps.python.org/pep-0638/#resolving-ambiguity][the statement form takes precedence at the start of a line]].
Inside an f-string, I kept the =!= in =f"{x!r}"= as the conversion specifier.
There are three [[https://peps.python.org/pep-0638/#defining-macro-processors][kinds of macro processors]].
- =STMT_MACRO= :: A statement macro. It receives the indented block as =body=.
- =SIBLING_MACRO= :: A statement macro without a block. It receives the next statement in the same block as =body=.
- =EXPR_MACRO= :: An expression macro.
If you use a macro you haven't imported, compilation fails with a =SyntaxError=.
#+begin_src console
$ cat undefined.py
print(quote!(a + b))
$ ./python undefined.py
File "/path/to/undefined.py", line 1
print(quote!(a + b))
^^^^^^^^^^^^^
SyntaxError: macro quote! is not defined
#+end_src
** The layer that expands macros
CPython parses the source into an AST and builds the symbol table and the bytecode from that AST, so I put macro expansion at the point where the compiler starts turning the AST into bytecode.
[[./resources/public/img/f4154e-pipeline.svg]]
The parser keeps each macro in the tree as an =ast.MacroStmt= or =ast.MacroExpr= node, and the compiler walks the tree in C to look for macros.
If it finds one, it converts the tree into Python objects and passes them to =macros._expand()=, which calls the processors from the outermost macro inward and expands the trees those processors return as well.
The compiler converts the expanded tree back into C structs, validates it, and passes it on to the symbol table and bytecode generation.
Expansion runs on every compilation, so macros work through =import=, =exec()=, and =compile()= alike, and since =ast.parse()= returns the tree before expansion, you can inspect the macro nodes as the parser left them.
#+begin_src console
$ ./python -c 'import ast; print(ast.dump(ast.parse("quote!(a)").body[0]))'
MacroStmt(name='quote', args=[Name(id='a')])
#+end_src
=quote!(a)= sits at the start of the line, so the parser reads it as a statement macro.
A layer in front of the parser decides how to treat keywords.
CPython's parser receives =finally= as a keyword token and can't read =finally!= as a name, so when the next character is =!=, I made that layer skip the keyword check and keep the token as a name.
If =!== follows, as in =x!=y=, the parser reads it as the comparison operator.
** StmtExpr: running a statement inside an expression
Some expression macros need to run a statement before they compute their value.
The [[https://peps.python.org/pep-0638/#ast-extensions][PEP]] defines a =stmt_expr= node for this, and this implementation provides it as =ast.StmtExpr(stmt, value)=, which runs =stmt=, then evaluates =value= and uses that as the value of the expression.
#+begin_quote
A new AST node called =stmt_expr= will be added, combining a statement and an expression. This new ast node will be a subtype of =expr=, but include a statement to allow side effects. It will be compiled to bytecode by compiling the statement, then compiling the value.
#+end_quote
As a test, I write =debug!=, which prints an expression and its value and then returns the value.
#+begin_src python
# mymacros.py に足す
@macros.macro_processor(macros.EXPR_MACRO, 1)
def debug(node):
tmp = f"$$debug_{node.lineno}_{node.col_offset}"
label = ast.unparse(node.args[0]) + " ="
show = ast.If(ast.Constant(True), [
ast.Assign([ast.Name(tmp, ast.Store())], node.args[0]),
ast.Expr(ast.Call(ast.Name("print", ast.Load()),
[ast.Constant(label), ast.Name(tmp, ast.Load())],
[])),
], [])
return ast.StmtExpr(show, ast.Name(tmp, ast.Load()))
#+end_src
For the =debug!= on line 3 of =debug.py=, the variable name becomes =$$debug_3_11=.
This follows [[https://peps.python.org/pep-0638/#hygiene-and-debugging][the naming that the PEP recommends to avoid collisions]], and you can't write such a name in source code, so it can't clash with your variables.
#+begin_quote
- All generated variable names should start with a =$=
- Purely artificial variable names should start =$$mname= where =mname= is the name of the macro.
- Variables derived from real variables should start =$vname= where =vname= is the name of the variable.
- All variable names should include the line number and the column offset, separated by an underscore.
#+end_quote
#+begin_src python
# debug.py
from! mymacros import debug
squares = [debug!(x * x) for x in range(3)]
print(squares)
print(True or debug!(1 / 0))
#+end_src
#+begin_src console
$ ./python debug.py
x * x = 0
x * x = 1
x * x = 4
[0, 1, 4]
True
#+end_src
Python evaluates =debug!= where it sits, both inside the comprehension and on the right of =or=, and it skips the right side of =True or ...=, so =1 / 0= doesn't run and stop the program.
The compiler translates =StmtExpr= into bytecode itself, so the statement runs where you place the macro, in Python's evaluation order.
If a =break=, =continue=, or =return= inside =stmt= leaves the =StmtExpr=, control jumps out in the middle of an expression and leaves values on the stack, so the compiler rejects such a tree with a =SyntaxError=.
#+begin_src python
# escape.py
import ast
tree = ast.parse("for x in y:\n f(E)\n")
call = tree.body[0].body[0].value
call.args[0] = ast.StmtExpr(ast.Break(), ast.Constant(None))
ast.fix_missing_locations(tree)
compile(tree, "<ast>", "exec")
#+end_src
#+begin_src console
$ ./python escape.py
Traceback (most recent call last):
File "/path/to/escape.py", line 7, in <module>
compile(tree, "<ast>", "exec")
~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^
File "<ast>", line 2
SyntaxError: 'break', 'continue' and 'return' cannot leave a statement expression
#+end_src
** Differences from the PEP
This implementation differs from the text of the PEP in these ways.
- The AST class names follow CPython's naming: =MacroStmt=, =MacroExpr=, and =StmtExpr=.
- The parser reads the block of a statement macro as Python statements. A line such as ="red" = 1= in the PEP's [[https://peps.python.org/pep-0638/#compile-time-checked-data-structures][bijection! example]] is a syntax error.
- The [[https://peps.python.org/pep-0638/#lexical-analysis][PEP]] specifies the macro name as a single =MACRO_NAME= token, but =tokenize= returns it as two tokens, =NAME= and =!=.
- The [[https://peps.python.org/pep-0638/#defining-macro-processors][PEP]] defines the =version= of a processor as the number that lets Python rebuild cached bytecode correctly. This implementation checks that =version= is an integer, but it doesn't rebuild cached bytecode when you change a processor.
The =bijection!= example in the PEP looks like this.
#+begin_src python
bijection! color_to_code, code_to_color:
"red" = 1
"blue" = 2
"green" = 3
#+end_src
** Trying it
You build it the same way as CPython, and with Nix, =nix develop nixpkgs#python315= gives you everything the build needs.
#+begin_src console
$ git clone https://github.com/conao3/cpython-pep638
$ cd cpython-pep638
$ ./configure --with-pydebug
$ make -j
$ ./python -m test test_macros
#+end_src
All 32 tests in =test_macros= pass, and the full CPython test suite passes as well, except for one test in =test_profiling= that checks the executable name of a child process and fails in the Nix environment.
The [[https://github.com/conao3/cpython-pep638#where-the-implementation-lives][Where the implementation lives]] section of the repository README lists what I added and where.