use strings to call functions

Jean-Michel Pichavant jeanmichel at sequans.com
Mon Feb 8 06:59:39 EST 2010


Klaus Neuner 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?
>
> Klaus
>
>   
You won't need anything else than defining the proper function to 
support the extension with the following code:


import os

class Handlers:

    class NoHandler(Exception):
        pass
   
    @staticmethod
    def txt(fileName):
        print 'I am processing a txt file'

    @staticmethod
    def tar(fileName):
        print 'I am processing a tar file'

    @classmethod
    def default(cls, fileName):
        raise cls.NoHandler("I don't know how to handle %s " % fileName)

for fileName in ['/tmp/test.txt', '/tmp/sdfsd.sfds']:
    _, extension = os.path.splitext(fileName)
    func = getattr(Handlers, extension.replace('.', ''), Handlers.default)
    try:
        func(fileName)
    except Handlers.NoHandler, exc:
        print exc


JM



More information about the Python-list mailing list