Search code examples
pythonmacroslispscheme

Python Macros: Use Cases?


If Python had a macro facility similar to Lisp/Scheme (something like MetaPython), how would you use it?

If you are a Lisp/Scheme programmer, what sorts of things do you use macros for (other than things that have a clear syntactic parallel in Python such as a while loop)?


Solution

  • Some examples of lisp macros:

    • ITERATE which is a funny and extensible loop facility
    • CL-YACC/FUCC that are parser generators that generate parsers at compile time
    • CL-WHO which allows specifying html documents with static and dynamic parts
    • Parenscript which is a javascript code generator
    • Various simple code-wrappers, e.g., error handlers (I have a with-gtk-error-message-handler that executes code and shows GtkMessageDialog if unhandled error occurs), executors (e.g., given a code, execute it in different thread; I have a within-main-thread macro that executes code in different threads; PCall library uses macros to wrap code to be executed concurrently)
    • GUI builders with macros (e.g., specify widgets hierarchy and widgets' properties and have a macro generate code for creation of all widgets)
    • Code generators that use external resources during compilation time. E.g., a macro that processes C headers and generates FFI code or a macro that generates classes definitions based on database schema
    • Declarative FFI. E.g., specifying the foreign structures, functions, their argument types and having macros to generate corresponding lisp structures, functions with type mapping and marshaling code
    • Continuations-based web frameworks for Common Lisp use macros that transform the code into CPS (continuation passing style) form.