I would like to invoke the following code in-situ wherever I refer to MY_MACRO
in my code below.
# MY_MACRO frameinfo = getframeinfo(currentframe()) msg = 'We are on file ' + frameinfo.filename + ' and line ' + str(frameinfo.lineno) # Assumes access to namespace and the variables in which `MY_MACRO` is called. current_state = locals().items()
Here is some code that would use MY_MACRO
:
def some_function: MY_MACRO def some_other_function: some_function() MY_MACRO class some_class: def some_method: MY_MACRO
In case it helps:
MY_MACRO
wherever I need it. Having something short and easy would be very helpful. locals().items()
(see this other question)Is this at all possible in Python? What would be the easiest way to get this to work?
Please NOTE that the macro assumes access to the entire namespace of the scope in which it's called (i.e. merely placing the code MY_MACRO
in a function would not work). Note also that if I place MY_MACRO
in a function, lineno
would output the wrong line number.
You can write an Excel macro in python to do whatever you would previously have used VBA for. Macros work in a very similar way to worksheet functions. To register a function as a macro you use the xl_macro decorator. Macros are useful as they can be called when GUI elements (buttons, checkboxes etc.)
Macros can only be written in Python. A macro can be a function or a class. In order for a function to be recognized as a macro, it must be properly labeled as a macro (this is done with a special macro decorator.
A macro is a compile-time function that transforms a part of the program to allow functionality that cannot be expressed cleanly in normal library code. The term “syntactic” means that this sort of macro operates on the program's syntax tree.
Here's a very simple Excel Vba macro – it takes an argument, writes a greeting message in cell B2 of the “Sheet1” tab. You can create any macro and run it with Python.
MacroPy is a project of mine which brings syntactic macros to Python. The project is only 3 weeks old, but if you look at the link, you'll see we have a pretty cool collection of demos, and the functionality you want can definitely be implemented using it.
On the other hand, python has some pretty amazing introspection capabilities, so I suspect you may be able to accomplish what you want purely using that functionality.
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()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With