[Tutor] Dynamically naming functions

Ed Singleton singletoned at gmail.com
Mon Mar 13 10:38:36 CET 2006

On 10/03/06, Kent Johnson <kent37 at tds.net> wrote:
> 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.

To be honest, this didn't seem that bizarre to me.  If I understand
properly (which I probably don't) functions are just callable objects
like any other callable object (or at least can be treated as such). 
Isn't this just a handy way of creating a nested object structure
that's readable?

> 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.

This makes sense, and I think I can see how I would use it.

To create a bunch of objects from some data (just name and start date):

for fname, startdate in data:
    def foo:
        start = ""
    setattr(foo, __name__, fname)
    setattr(foo, start, startdate)

Sorting out the nesting should be fairly straightforward (if the above works).



More information about the Tutor mailing list