use strings to call functions

Wojciech Muła wojciech_mula at poczta.null.onet.pl.invalid
Mon Feb 8 12:37:49 CET 2010


Klaus Neuner <klausneuner72 at googlemail.com> wrote:

> > handlers = {
> >     ".txt" : handle_txt,
> >     ".py" : handle_py,
> >     # etc
> >     }
> >
> 
> That is exactly what I would like to avoid: Having to map the function
> 'handle_txt' to '.txt'. Firstly, because I don't want to repeat
> anything and secondly, because I will one day add a new function and
> forget to add its name to the dictionary.

Use dictionary mantained by runtime:

def handle(extensions):
	funname = "handle_" + extension
	return globals()[funname]
	
handle('txt') # => function handle_txt

w.



More information about the Python-list mailing list