PEP 638 – Syntactic Macros
12 days ago
- #Macros
- #Python
- #Language Extensions
- PEP 638 proposes adding syntactic macros to Python, allowing compile-time AST transformations.
- Macros enable domain-specific language extensions without adding complexity to Python's core.
- Motivation includes avoiding controversial new features and supporting domain-specific needs like data science.
- Macros can trial new language features before official inclusion, improving quality and reliability.
- Syntax includes statement and expression forms, with `import!` and `from!` for macro imports.
- Macro processors are defined with a callable, kind, version, and optional additional names.
- New AST nodes (`macro_stmt`, `macro_expr`, `stmt_expr`) are introduced to support macros.
- Examples include compile-time data structure checks, domain-specific parsers, and zero-cost annotations.
- Backwards compatibility is maintained, with performance impact only on macro-using code.
- Implementation requires making AST nodes immutable Python objects for efficiency.