Getting in to metaprogramming

Steven D'Aprano steven at
Thu Nov 27 01:29:05 CET 2008

On Thu, 27 Nov 2008 06:41:47 +0200, 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)

GUI designer. You write a program to let the user create code by clicking 
buttons, dragging objects, drawing lines, etc. The GUI designer may use 
classes, but the purpose of those classes is to generate source code.

Testing code speed... you might have some functions with a loop, and you 
want to unroll the loop as an optimization. If you have one function, you 
can unroll it yourself. If you have a hundred such functions, you might 
want to write a program to do it. (Yes, I'm stretching...)

Don't like that Python doesn't optimize tail-recursion? Then write a 
source-code analyzer that detects tail-recursion and re-writes the 
function using a while loop. 

>> Thinking further back, when I was young and programming in Apple's
>> Hypercard 4GL, I used to frequently use Hypercard scripts to generate
>> new Hypercard scripts. That was to work around the limitations of the
>> scripting language.
> What sort of stuff did you do, and would having had simple OO available
> have rendered it unnecessary?

It's been 20-odd years, and the examples were pretty trivial... I don't 
really recall exactly, but it would have been something like this:

* design a GUI involving lots of buttons on screen, each one with quite 
similar but not identical code;

* since Hypercard didn't have a layout manager, write a script to 
generate each button, place it where needed, and set the button's code.

Hypercard did have a message passing hierarchy (like inheritance for 
objects), so often you could take the button's code and place it in a 
higher level of the hierarchy (the card, the background, the stack), but 
there were odd cases where that wasn't enough.

Another example: Hypercard had a very limited number of GUI elements 
(text fields and buttons, basically) but I designed a slider control 
using a few buttons, each button with a custom script. To avoid needing 
to create and place the buttons by hand each time I wanted a slider, I 
had a script that did it for me. The script not only created the buttons, 
but it created the scripts used by the buttons. This wasn't as difficult 
as it sounds -- it was basically taking a template and doing some text 
replacements, then telling the button to use it as a script.


More information about the Python-list mailing list