Automatic Code Generation

Ian Bicking ianb at colorstudy.com
Mon Oct 6 14:34:23 EDT 2003


On Monday, October 6, 2003, at 07:24 AM, Rasmus Fogh wrote:
>> I would disagree that code generation is a good solution to these, or
>> nearly any case.  Specifically in Python, code generation isn't
>> necessary because you can build objects and classes dynamically.  So 
>> if
>> you have a non-Python representation of the object or class, you can
>> write code to dynamically create that class, instead of writing code
>> that writes code.
>>
>
> Building the code dynamically would certainly be an alternative, so 
> code
> generation is not necessary (i.e. unavoidable).

Not to belabor the point, but I wouldn't propose just dynamically 
creating the code.  If you are generating *code*, there's nothing wrong 
with writing it to disk and turning it into a compilation step (it can 
be nice if you can hide that compilation, but it's not that big a deal).

I most cases -- especially using new-style classes and descriptors -- 
you do not need to generate code.  For instance, SQLObject (an 
object-relational mapper that I wrote) generates only a small amount of 
code (a very small number of eval'ed lambda statements).  Several 
similar packages have you write a separate model, and then compile that 
module into code, which sounds like the same kind of mechanism you are 
using for your models.

I do some of this with a metaclass, but that is largely to make the 
Python classes look prettier.  The real work happens in class methods 
that add and remove attributes from the class itself.  In fact, most of 
it doesn't even require new-style classes, but simply takes advantage 
of the ability to modify classes after they have been created.

Depending on the environment, there can be a performance overhead.  I'm 
biased to persistent applications, so the startup time doesn't concern 
me as much.  Or maybe I don't like to worry about startup time, so I 
use persistent applications ;)

--
Ian Bicking | ianb at colorstudy.com | http://blog.ianbicking.org






More information about the Python-list mailing list