use strings to call functions
Steve Holden
steve at holdenweb.com
Mon Feb 8 07:08:15 EST 2010
Klaus Neuner wrote:
>> A file extension is not necessarily 3 chars long.
>
> No, of course not. But it is, if I choose to use only (self-made) file
> endings that are 3 chars long. Anyway, it was just an example.
>
>> 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. (This is not severe if there
> is only one dictionary for mapping functions, but it will make life a
> lot harder, if a lot of mappings of this kind are used.)
>
> What I want is calling the string directly. In Prolog, I would use
> something like:
>
> get_file_ending(File, Ending),
> Predicate =.. [Ending, File],
> call(Predicate).
>
>
--
Steve Holden +1 571 484 6266 +1 800 494 3119
PyCon is coming! Atlanta, Feb 2010 http://us.pycon.org/
Holden Web LLC http://www.holdenweb.com/
UPCOMING EVENTS: http://holdenweb.eventbrite.com/
More information about the Python-list
mailing list