use strings to call functions

Stefan Behnel stefan_ml at
Mon Feb 8 13:03:10 CET 2010

Klaus Neuner, 08.02.2010 11:57:
> 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?

Others have already pointed you to the approach of using a dict, or a
module/class namespace with functions/methods to do this. Either of the
latter two would be my favourite, depending on the complexity of the
handlers. A class is more suitable as a container for short, highly
correlated handlers, whereas a module makes more sense for handlers that do
rather different things, or that are longer than a single function. A
mixture of the two, e.g. a module of classes, where an entire class is used
to implement a complete handler over several methods (potentially including
some inheritance hierarchy between handlers that share functionality) might
also be a solution. Note that objects can be callable in Python (special
method __call__), you can exploit that here.

What you are implementing here is commonly called a dispatch mechanism,
BTW. There are several ways to do that, also within in Python. A web search
should reveal some more.


More information about the Python-list mailing list