I would like to invoke the following code in-situ wherever I refer to MY_MACRO
in my code below.
# MY_MACRO
frameinfo = getframeinf
I'm not sure if this is a good solution, but it's at least worth considering a macro preprocessor.
There are a few different extend-Python-with-macros projects, or wider projects that should make such a thing easier to do, but I only have expired links for all of them (Logix, MetaPython, Mython, Espy)… It might be worth looking for current links and/or newer/liver projects.
You can use something like m4
or cpp
, or something more powerful, or even build one yourself. But really, you've just got a small, static set (so far, one) of purely textual macros. At worst you have to detect the indentation level of MY_MACRO
and add that to the start of each line, which is trivial to do in a regex. Meaning sed
, or a 3-liner Python script, can be your preprocessor.
However, there are two problems, or at least annoyances.
First, you need to preprocess your files. If you're already using C extension modules or generated code or any other code that needs you to setup.py
(or make
or scons
or whatever) before you can run it, or you're using an IDE where you just hit cmd-R or ctrl-shift-B or whatever to test your code, this isn't a problem. But for the typical edit-test loop with a text editor in one window and an interactive interpreter in another… well, you've just turned it into an edit-compile-test loop. Ugh. The only solution I can think of is an import hook that preprocesses every file before importing it as a module, which seems like a lot of work for a small benefit.
Second, your line numbers and source (from MY_MACRO
itself, as well as from tracebacks and inspect.getsource
and so on) are going to be the line numbers of the preprocessed files, not the original source that you have open for editing. Since your preprocessed files are pretty readable, that isn't terrible (not as bad as coding CoffeeScript and debugging it as JavaScript, which most of the CoffeeScript community does every day…), but it's definitely an annoyance.
Of course one way to solve this is to build your own macro processor into the interpreter, at whichever stage in the parse/compile process you want. I'm guessing that's a whole lot more work than you want to do, but if you do, well, Guido always prefers to have an actual working design and implementation to reject instead of having to keep rejecting vague suggestions of "Hey, let's add macros to Python". :)