Adding Macros to Python

前端 未结 7 1138
无人及你
无人及你 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:25

    How about a function you can call? This function accesses the caller's frame, and rather than using locals(), uses frame.f_locals to get the caller's namespace.

    def my_function():
        frame = currentframe().f_back
        msg = 'We are on file {0.f_code.co_filename} and line {0.f_lineno}'.format(frame)
        current_state = frame.f_locals
        print current_state['some_variable']
    

    Then just call it:

    def some_function:
        my_function()
    
    def some_other_function:
        some_function()
        my_function()
    
    class some_class:
      def some_method:
         my_function()
    

提交回复
热议问题