ANN: MacroPy: bringing Macros to Python

Haoyi Li haoyi.sg at gmail.com
Wed Apr 24 00:24:09 EDT 2013


MacroPy is a pure-python library that allows user-defined AST rewrites as part of the import process (using PEP 302). In short, it makes mucking around with Python's semantics so easy as to be almost trivial: you write a function that takes an AST and returns an AST, register it as a macro, and you're off to the races. To give a sense of it, I just finished implementing Scala/Groovy style anonymous lambdas:

map(f%(_ + 1), [1, 2, 3])
#[2, 3, 4]

reduce(f%(_ + _), [1, 2, 3])
#6

...which took about half an hour and 30 lines of code, start to finish. We're currently working on implementing destructuring-pattern-matching on objects (i.e. like in Haskell/Scala) and a clone of .NET's LINQ to SQL.

It's still very much a work in progress, but we have a list of pretty cool macros already done, which shows off what you can do with it. If anyone else was thinking about messing around with the semantics of the Python language but was too scared to jump into the CPython internals, this offers a somewhat easier path.

Thanks!
-Haoyi



More information about the Python-list mailing list