[Tutor] Dynamically naming functions

Kent Johnson kent37 at tds.net
Fri Mar 10 12:36:10 CET 2006


Ed Singleton wrote:
> How does one go about creating functions, classes, or callable objects
> when you don't know their name in advance? (For example you want to
> read their names in from a text file or database).
> 
> I want to use this in a few different places.  For example Faces, the
> Python Project Management Planner Tool Thingy, uses nested functions
> to put tasks within a project:
> 
> def MyProject():
>     start = "2006-03-06"
>     resource = Me
> 
>     def Task1():
>         start = "2006-03-13"
> 
>     def Task2():
>         effort = "1w"
> 
> I'd like to load these from a database (using SQLObject), but I'm not
> sure how I can define the name of the function from a filed in a
> database (or read in from a text file).

This is truly bizarre use of nested functions. Faces must be looking at 
the compiled function objects to pick this out.

I would look into the Project objects themselves and see if there is a 
way to create them dynamically, rather than trying to build this 
structure dynamically at run time.
> 
> I'd also like to be able to do this in CherryPy/TurboGears so that I
> can create a dynamic site structure based on fields in a database.

This seems more practical. I would define a class that is configured by 
the database can be used as a CP model object. Then you can insert the 
class into the CP site structure using setattr().

In general you can set an attribute of an object using setattr():
   setattr(foo, 'bar', 3)
is the same as
   foo.bar = 3
but the attribute name is specified as a string so it can be determined 
at runtime.

Kent
> 
> Thanks
> 
> Ed
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
> 
> 




More information about the Tutor mailing list