[BEGINNER] meta-functions

Daniel Yoo dyoo at hkn.eecs.berkeley.edu
Wed Dec 26 00:32:57 EST 2001

Igor Mozetic <igor.mozetic at uni-mb.si> wrote:
: A simple question from a newbie, sorry.

: I have functions defined normally, def fname(arg1,arg2):
: and also represented as tuples (fname, arg1, arg2),
: to use them by apply(fname, (arg1,arg2)) - no problem.

: How do I make a comparison:  fname == 'string' ?

It sounds like you're doing some data-directed programming.  Out of
curiosity, would it be ok to store the function's name within your
tuple as well?  For example:

def square(x): return x*x
def sqrt(x): return x**(.5)

def getFunction(name):
    functions = [("square", square),       ## A dictionary may be a
                 ("sqrt", sqrt)]           ## better data structure
                                           ## for this.
    for n, f in functions:
        if n == name: return f
    return None
while 1:
    f_name = raw_input("Enter function name:")
    f = getFunction(f_name)
    if not f: break
    print f(42)

This approach doesn't take too much advantage of many Python-specific
features.  Hope this helps!

More information about the Python-list mailing list