Getting in to metaprogramming

Aaron Brady castironpi at gmail.com
Tue Nov 25 11:41:10 CET 2008


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.



More information about the Python-list mailing list