Adding Macros to Python

前端 未结 7 1172
无人及你
无人及你 2021-02-02 07:41

I would like to invoke the following code in-situ wherever I refer to MY_MACRO in my code below.

# MY_MACRO
frameinfo = getframeinf         


        
7条回答
  •  感动是毒
    2021-02-02 08:29

    The use of exec is frowned upon, but it ought to do the trick here. For example, take the following macro:

    MY_MACRO = """
    print foo            
    """
    

    and run it by using the following code:

    foo = "breaking the rules"
    exec MY_MACRO in globals(),locals() 
    

    Always be careful with exec, because it can have strange side-effects and opens up opportunities for code injection.

提交回复
热议问题