View Single Post
  #2 (permalink)  
Old 02-08-2010, 10:11 AM
Bruno Desthuilliers
Guest
 
Posts: n/a
Default Re: use strings to call functions

Klaus Neuner a écrit :
> 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:]


A file extension is not necessarily 3 chars long.

> apply_func(func, file)
>
> Can something of this kind be done in Python?


The simplest (and canonical) solution is to use a dict:

def handle_txt(path):
# code here

def handle_py(path):
# code here

etc...

def handle_default(path):
# for anything else


handlers = {
".txt" : handle_txt,
".py" : handle_py,
# etc
}


import os

def handle_file(path):
dummy, ext = os.path.splitext(path)
handler = handlers.get(ext, handle_default)
return handler(path)

HTH
Reply With Quote