Python Macros: Use Cases?

后端 未结 17 2102
甜味超标
甜味超标 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:56

    Hy, For my own use, I created a Python module (Espy) that allows macro definitions with arguments, loop and conditional code generation: You create a source.espy file, then launch the appropriate function, then source.py is generated.

    It allows syntaxes as following:

    macro repeat(arg1):
        for i in range(%arg1%):
            socket
        print "stop"
       ...
    repeat(5):
        print "Hi everybody"
        print "See you soon"
    

    is equivalent to:

    ...
    for i in range(5):
        print "Hi everybody"
        print "See you soon"
    print "stop"
    

    Other syntax:

    macro doit(arg1):
        for i in %arg1%:
            socket suit(arg2):
                socket
                print %arg2%
            socket check(arg3):
                if %arg2%==%arg3%:
                    socket
    ...
    #use
    doit(range(10)):
        suit(result):
            result=i*i
        check(result,25):
            print "I knew that 5*5 == 25"
    

    is equivalent to:

    for i in range(10):
        result=i*i
        print result
        if result==25:
            print "I knew that 5*5 == 25"
    

    More, Espy has 2 functions: "macro for" and "macro if". An example:

    macro for v in [6,10,12,20,23]:
        macro if 7<%v%<22:
            True:
                print "At %v%, I'm awake."
            False:
                print "At %v%, I'm sleeping."
    

    is translated by Espy in:

    print "At 6, I'm sleeping."
    print "At 10, I'm awake."
    print "At 12, I'm awake."
    print "At 20, I'm awake."
    print "At 23, I'm sleeping."
    

    Complete documentation and free download can be found here: http://elp.chronocv.fr

    I use this module in many cases. It permits more structured and shorter codes. With it I generated 65000 lines of clear and efficient python code from 1000 lines of espy code for a new chess engine project (still in progress).

    If Python could include macros in futur release, it'd become more impressive.

提交回复
热议问题