Getting in to metaprogramming

Stef Mientki stef.mientki at gmail.com
Tue Nov 25 13:12:38 EST 2008


Rafe wrote:
> 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.
>   
I use Python's own triple quoted string as a generator for the GUI, like 
this:
    GUI = """
    self.NB       ,wx.Notebook     ,style = wx.NO_BORDER
      self.Grid   ,Base_Table_Grid ,None, data_values, data_types, data_defs
      Panel2      ,PanelVer, 11    ,name  = "Page2"
        list1     ,wx.ListCtrl     ,style = wx.LC_REPORT
    """
cheers,
Stef
> 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
> --
> http://mail.python.org/mailman/listinfo/python-list
>   




More information about the Python-list mailing list