use strings to call functions

Bruno Desthuilliers bruno.42.desthuilliers at websiteburo.invalid
Mon Feb 8 06:11:14 EST 2010


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



More information about the Python-list mailing list