dynamically generating function assignent

Xtian Muirhead xtian_the_great at hotmail.com
Mon Nov 1 19:26:32 EST 1999


Bjorn Pettersen <bjorn at roguewave.com> wrote in message
news:51C9F3C392D0D111A15600A0C99E64A9AF5605 at localhost...
> You can do:
>
> fn = eval('func_' + 'a') # look it up in the environment
> fn()
>
> -- bjorn
>
> > -----Original Message-----
> > From: anantk at my-deja.com [mailto:anantk at my-deja.com]
> > Sent: Monday, November 01, 1999 11:19 AM
> > To: python-list at python.org
> > Subject: dynamically generating function assignent
> >
> >
> > Hi,
> >
> >   Here is my problem. I have defined say 12 pairs of functions
> >
> > func_a()
> > parse_func_a()
> >
> > func_b()
> > parse_func_b()
> >  .
> > .
> > func_l()
> > parse_func_l()
> >
> >   A file contains a series of strings which are the names of these
> > functions eg:
> >
> > a
> > c
> > f
> > b
> >
> >   Now for each of these strings I need to call the two functions
> > func_<x>(), and parse_func_<x>(), where <x> is the name of
> > the function
> > that string refers to.
> >
> >   I know you can do something like
> >   call = func_a, and call effectively gets assigned to func_a. My
> > question is how can I generate the RHS of this assignment dynamically?
> > So that all I have to do is
> >
> >   <variable> = <next line in file>
> >   call1 = func_<variable>
> >   call2 = parse_func_<variable>
> >   call1()
> >   call2()
> >
> >   Any help would be appriciated.
> >
> >   Thanks
> >
> > -- Anant

Another way would be to load all the functions into a dictionary.
e.g:

def func_1():
    <blah>

def parse_func_1():
    <blah>

...

functions = {'1':(func_1,parse_func_1),
             'a':(func_a, parse_func_a),
                ...}

Then you could look up call1 and call2:

call1, call2 = functions[valueFromFile]
call1()
call2()

This could be easier to catch cases where the value from the file
doesn't match any of the functions defined. (And I prefer this kind
of static lookup to a dynamic lookup. That's just a bias, I guess.
Suffice it to say that both of these ways are nicer than a whole heap
of elifs. (I guess if you had hundreds of these functions, you wouldn't
want to have to type out all of them in a dictionary (with the
attendant likelihood of making an error).))

Xtian

xtian at regurgitator.zzn.com

"Most people don't realise that large pieces of coral, which have been
painted brown and attached to the skull by common wood screws, can make
a child look like a deer."







More information about the Python-list mailing list