use strings to call functions

Dave Angel davea at ieee.org
Mon Feb 8 06:30:34 EST 2010


Klaus Neuner 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?
>
> Klaus
>
>
>   
You perhaps were intending to use the file extension , rather than the 
last three characters of the name.  If so, consider os.path.splitext().  
And you shouldn't shadow the builtin *file* type with a variable of the 
same name.

More directly to your question, best suggestion is to build a (const) 
dictionary:

apply_func = { "xyz":xyz, "abc":abc }

which maps the strings to functions.  This line can be at outer scope, 
as long as it follows all the appropriate function definitions.  Notice 
that the individual functions need not be in the same module, if you use 
a fully qualified name in the dictionary.  And of course, there's no 
necessity of naming the function exactly the same as the extension.  So 
you could implement the functions in another module 'implem", and use 
the following:

import implem
apply_func = { "xyz":implem.process_xyz_files, 
"abc":implem.process_abc_files }

Now, you use it by something like:
     dummy, func_ext = os.path.splitext(my_filename)
     apply_func(func_ext, my_filename)

(all code untested)

DaveA




More information about the Python-list mailing list