calling variable function name ?

TkNeo tarun.kap at gmail.com
Wed Apr 30 11:57:45 EDT 2008


On Apr 8, 7:51 pm, George Sakkis <george.sak... at gmail.com> wrote:
> On Apr 8, 3:52 pm,TkNeo<tarun.... at gmail.com> wrote:
>
> > I don't know the exact terminology in python, but this is something i
> > am trying to do
>
> > i have 3 functions lets say
> > FA(param1,param2)
> > FB(param1,param2)
> > FC(param1,param2)
>
> > temp = "B" #something entered by user. now i want to call FB. I don't
> > want to do an if else because if have way too many methods like
> > this...
>
> > var = "F" + temp
> > var(param1, param2)
>
> Try this:
>
> func = globals()["F" + temp]
> func(param1, param2)
>
> HTH,
> George



George - Thanks for your reply but what you suggested is not working:

def FA(param1,param2):
    print "FA" + param1 + " " + param2
def FA(param1,param2):
    print "FB" + param1 + " " + param2
def FA(param1,param2):
    print "FC" + param1 + " " + param2

temp = sys.argv[1]

func = globals()["F" + temp]
func("Hello", "World")


I ran the script with first parameter as B and i get the following
message
KeyError: 'FB'




More information about the Python-list mailing list