[Tutor] Converting code to string

Kent Johnson kent37 at tds.net
Fri Aug 24 16:06:49 CEST 2007


Bernard Lebel wrote:
> In the task I'm currently having, I have to dynamically create a
> certain number of layout elements along its logic. The number of
> elements to create changes from one execution to the next, as it is
> driven by the user input. Since properpty plugins do not support such
> dynamic creation, my only solution is with the "on-the-fly" approach.
> 
> Now what I'd like to do is to create "real" functions, not strings,
> and convert them into strings for logic injection.

I think the inspect module is as good as you are going to get and it is 
just looking up the source code for a function and giving it back to you 
so it won't work with any kind of dynamic function, for example a 
function created inside a closure would not have a useful string 
representation in source.

Maybe you should look instead at flexible ways of creating the strings 
you need, some kind of template language. There are some simple ones in 
the Python Cookbook:
http://aspn.activestate.com/ASPN/search?query=template&x=0&y=0&section=PYTHONCKBK&type=Subsection
http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/52305

and quite a few more that have been developed for Web server use:
http://wiki.python.org/moin/Templating

Kent


More information about the Tutor mailing list