Python Macros: Use Cases?

后端 未结 17 2084
甜味超标
甜味超标 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 18:39

    See also this question: Pythonic macro syntax

    0 讨论(0)
  • 2021-01-30 18:42

    I'd use it to wrap yield to enable me to build more powerful generator pipelines.

    0 讨论(0)
  • 2021-01-30 18:42

    Possibly if you want the source code at runtime such as for debugging (say printf debugging an expression's value with the name of it so you don't have to write it twice).

    The only way I could think of to do it in python is to pass a string to eval.

    0 讨论(0)
  • 2021-01-30 18:43

    Currently, the only way features can be added to Python the language is through a PEP (Python Enhancement Proposal). This can be slow, and doesn't help you in the cases when you want to add a feature to the language that is only useful for your use case.

    For example, there's a PEP to add a do-while loop. This will probably be added to Python, but the PEP was created in 2003. I'd like to write do-while loops today, and I could do that if Python had macros.

    Similarly, there was a PEP to add labelled break and continue but this was rejected. If labelled break statements would make my code clearer, I could implement them with a macro.

    PEPs aside, I would also like an unless macro. Rather than writing:

    if not is_superman():
        dodge_bullet()
    

    I could write:

    unless is_superman():
        dodge_bullet()
    

    I'd like a case macro (often called cond in Lisp). Rather than writing:

    if x == FOO:
        do_stuff_with_foos()
    elif x == BAR:
        do_stuff_with_bars()
    elif x == BAZ:
        do_stuff_with_bazs()
    

    I could write:

    switch x:
       case FOO:
           do_stuff_with_foos()
       case BAR:
           do_stuff_with_bars()
       case BAZ:
           do_stuff_with_bazs()
    

    These would be straightforward to implement as macros. More complex, useful macros would include:

    • Ruby style string interpolation e.g. "hello there {user}" (probably best implemented as a reader macro)
    • Pattern matching

    Currently, these are only features in other languages. With macros, I could add them to Python. I could even write PEPs that included an example implementation. (Some PEPs already do this, but they are forced to modify the C source of the interpreter itself.)

    0 讨论(0)
  • 2021-01-30 18:44

    There's a mailing list posting (archive.org mirror) which explains this rather well. The post is about Perl, but it applies to Python just as well.

    0 讨论(0)
  • 2021-01-30 18:44

    Some uses cases I have seen before include making class factories or stripping logging statements out of production code.

    0 讨论(0)
提交回复
热议问题