Getting in to metaprogramming

Terry Reedy tjreedy at
Thu Nov 27 19:59:21 CET 2008

Hendrik van Rooyen wrote:
>  "Terry Reedy" <tjreedy at> wrote:
>> Hendrik van Rooyen wrote:
>>> I am using the term in the restricted sense of Python writing Python source.
>>> Given that, can anybody think of an example that you could not do with
>>> a class?  (excepting the "stored procedure" aspect)
>> I am not sure I understand your question.
>> def iterize(recursive_function_text):
>>      <code to parse input and fill a template>
>>      return equivalent_iterative_function_text
>> where input and output are both Python code.  If one were to implement
>> this by compiling the input to AST form and then walking the tree, the
>> AST node classes would be involved, but I would scarely say the
>> translation was done by the classes, as opposed to functions which might
>> or might not be attacked to a class as methods.
> I am not sure I understand the answer - if the input and output are both
> bits of python source, then the output must be stored and evaluated or
> imported to get it executed, right?

Yes. I would couple the above with

def iterfunc(rtext):
     itext = iterize(rtext)
     <code to exec itext to make function object>
     return ifunc

The text transform is the hard part and should be separate for testing 
and possible output for optimization or reuse elsewhere.

The scenario I have in mind is
1. write program with recursive function and test
2. triple-quote function text and wrap with function call; retest.

Yes, Steven's tail recursion example is example of above.

> Now if this is the case, my question has to do with whether it is always
> possible to put the equivalent code in a class, and instantiating it so that
> it is either immediately executed or ready for immediate execution.  My
> gut feel tells me that it should always be possible, but I have often had
> wrong hunches.
> Not sure if this makes it any clearer.

I am not sure what you mean by 'do with a class'.  A class is an active 
namespace in that it creates and initializes instances and does a bit 
extra with method calls, but it is otherwise a passive namespace container.

Any code can be put into class methods, but I do not see any reason to 
do so for this example.

Terry Jan Reedy

More information about the Python-list mailing list