[Tutor] Dynamically naming functions

Alan Gauld alan.gauld at freenet.co.uk
Fri Mar 10 13:00:28 CET 2006


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

First point, names of functions are no different to names of other things.

def f(x):
    y = blah....
    return y

is essentialy the same as saying

f = lambda x: blah...

lambda defines a nameless (aka anonymous) function and then assigns that
function to the variable called f.

Of course Pythons lambda construct is a bit brain dead so we can achieve
the same result with just assigning an existing function to a new name

def f(x):
   y = nblah...
   return y

g = f

Now g is a new name that refers to the function called f.

And with nested function definitions we can write functions that
return functions:

def makeMultiplyAndAdd(constants):
    def f(x):
        return constant[0] * constant[1] + x
    return f


> 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 field in a database (or read in from a text file).

Same way as you would for any other kind of variable.
This has been discussed many times and there is some trickery you
can do using the built in dictionaries that Python uses for its namespaces.
But the biggest proiblem with introducing new names at run time is:
How does the existing code get to know about those names that
didn't exist when the code was written? Ypou need to have the code
go exploring for names, work out what kind ioopf value they hold etc...
It all gets very messy and complicated and fault prone.

So the normal way to do this is to use a dictionary.
The dictionary is a collection of names with values asociated with them.
Those values can be functions or classes or anything else.

Now your code can access the new names by using standard
dictionary iterators etc. All you need are some conventions around
how many parameters the functions have, their types etc.

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

Dynamic site structure shouldn't need dynamic creation of functions
although the structure might need to be dynamically loaded into a
data structure in the code. It might also be a parameter of the functions.

But as always remember that dynamic anything usually means
much harder to maintain. All of your backup/archiving tools and error
reporting tools etc will need to understand your dynamic structure too.
Dynamic sounds like fun but usually means grief and is only justified
as a last resort IMHO!

But if you must go dynamic Python is as good a language to do it
in as you'll get.

Alan G. 



More information about the Tutor mailing list