use strings to call functions

OdarR olivier.darge at gmail.com
Mon Feb 8 14:28:53 EST 2010


On 8 fév, 11:57, Klaus Neuner <klausneune... at googlemail.com> wrote:
> Hello,
>
> I am writing a program that analyzes files of different formats. I
> would like to use a function for each format. Obviously, functions can
> be mapped to file formats. E.g. like this:
>
> if file.endswith('xyz'):
>     xyz(file)
> elif file.endswith('abc'):
>     abc(file)
>
> ...
>
> Yet, I would prefer to do something of the following kind:
>
> func = file[-3:]
> apply_func(func, file)
>
> Can something of this kind be done in Python?


and with eval(), did you try ?

import sys

def functext():
    print "texte"

def funcdoc():
    print "doc"

def funcabc():
    print "abc"


if __name__ == "__main__":
    #replace filename with suitable value
    filename = sys.argv[1].split('.')[1]
    try:
        eval('func' + filename + '()')
    except:
        print 'error'




More information about the Python-list mailing list