use strings to call functions

Gary Herron gherron at islandtraining.com
Mon Feb 8 14:47:40 EST 2010


OdarR wrote:
> On 8 fév, 11:57, Klaus Neuner <klausneune... at googlemail.com> wrote:
>   
>> 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:]
>> apply_func(func, file)
>>
>> Can something of this kind be done in Python?
>>     

I may have missed a bit of this thread -- so I have to ask:  Has anyone 
mentioned using getattr yet?  It's a way of looking up *any* attribute 
using a string to specify the name.  Like this for your particular example:

class Functions:  # This could be a module instead of a class
  def xyz(...):
      ...
  def abc(...):
      ...
  ... and so on ...


ext = os.path.splitext(file) # Parses out the extension
fn = getattr(Functions, ext) # Lookup the correct function
fn(...) # and call it

Gary Herron





More information about the Python-list mailing list