Adding Macros to Python

macropy, python

Solution

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.

Problem

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: - One of the reasons why I would like to have this ability is because I would like to avoid repeating the code of `MY_MACRO` wherever I need it. Having something short and easy would be very helpful. - Another reason is because I want to embed an IPython shell wihthin the macro and I would like to have access to all variables in `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.

Original source

Related problems