Python Macros: Use Cases?

后端 未结 17 2272
甜味超标
甜味超标 2021-01-30 18:37

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 y

17条回答
  •  青春惊慌失措
    2021-01-30 19:03

    This is a somewhat late answer, but MacroPy is a new project of mine to bring macros to Python. We have a pretty substantial list of demos, all of which are use cases which require macros to implement, for example providing an extremely concise way of declaring classes:

    @case
    class Point(x, y)
    
    p = Point(1, 2)
    print p.x   # 1
    print p     # Point(1, 2)
    

    MacroPy has been used to implement features such as:

    • Case Classes, easy Algebraic Data Types from Scala
    • Pattern Matching from the Functional Programming world
    • Tail-call Optimization
    • Quasiquotes, a quick way to manipulate fragments of a program
    • String Interpolation, a common feature in many languages, and Pyxl.
    • Tracing and Smart Asserts
    • PINQ to SQLAlchemy, a clone of LINQ to SQL from C#
    • Quick Lambdas from Scala and Groovy,
    • Parser Combinators, inspired by Scala's.

    Check out the linked page to find out more; I think I can confidently say that the use cases we demonstrate far surpass anything anyone's suggested so far on this thread =D

提交回复
热议问题