use strings to call functions

Tim Golden mail at timgolden.me.uk
Mon Feb 8 06:50:02 EST 2010


On 08/02/2010 11:26, 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).

You basically need a getattr lookup. If you're prepared to instantiate
a class or to import a handlers module then you can just look up against
that:

<handlers.py>
def handle_py (stuff):
   "print handling py"

def handle_default (stuff):
   "print handling default"

</handlers.py>

<main>
import handlers

ext = "py"
handler = getattr (handlers, "handle_" + ext, handlers.handle_default)
handler ("stuff")

</main>

You can do the equivalent by having a Handlers class with
the appropriate methods (handle_py, etc.) and which
you then instantiate.

If you want to keep everything in one module, you should be
able to achieve the same effect by looking the module up
in sys.modules and then proceeding as above:

<whatever.py>
import sys

def handle_py (stuff):
   print "handling py"

def handle_default (stuff):
   print "handling default"

ext = "py"
me = sys.modules[__name__]
handler = getattr (me, "handle_" + ext, me.handle_default)
handler ("blah")

</whatever.py>

(All untested...)

TJG



More information about the Python-list mailing list