Getting in to metaprogramming

Rafe rafesacks at gmail.com
Tue Nov 25 12:12:18 CET 2008


On Nov 25, 5:41 pm, Aaron Brady <castiro... at gmail.com> wrote:
> On Nov 25, 4:08 am, Rafe <rafesa... at gmail.com> wrote:
>
> > Hi,
>
> > In the name of self-education can anyone share some pointers, links,
> > modules, etc that I might use to begin learning how to do some
> > "metaprogramming". That is, using code to write code (right?)
>
> > Cheers,
>
> > - Rafe
>
> Python programs can generate code for themselves.
>
> >>> for i in range( 10 ):
>
> ...   d= { 'cls': i }
> ...   s="""
> ... class Cls%(cls)s:
> ...   def meth%(cls)s( self, arg ):
> ...     print 'in meth%(cls)s, arg:', arg
> ... """% d
> ...   exec( s )
> ...   s= """
> ... inst%(cls)s= Cls%(cls)s()
> ... """% d
> ...   exec( s )
> ...>>> inst0.meth0( "arg" )
> in meth0, arg: arg
> >>> inst1.meth1( "arg" )
> in meth1, arg: arg
> >>> inst2.meth2( "arg" )
>
> in meth2, arg: arg
>
> The 'Cls0', 'Cls1', 'Cls2' repetitiveness is taken care of with a for-
> loop.

Michele, I am thinking about python which writes python. Which makes
Aaron's post accurate to my needs. More specifically, I am considering
what it might be like to use python to build a script file which can
be executed later. Until now I planned to store info to XML and then
parse it to run later. There are good reasons that generating a script
file would be more useful for me.

Aaron, Is it really as simple as gathering strings of code? Sort of
like generating HTML or XML directly? Is there any other framework or
pattern set that is worth looking in to?

Thanks for helping me explore this.

- Rafe



More information about the Python-list mailing list