Refactoring; arbitrary expression in lists

Frans Englich frans.englich at
Wed Jan 12 19:16:23 CET 2005

As continuation to a previous thread, "PyChecker messages", I have a question 
regarding code refactoring which the following snippet leads to:

> > Function (detectMimeType) has too many returns (11)
> >
> > The function is simply a long "else-if" clause, branching out to
> > different return statements. What's wrong? It's simply a "probably ugly
> > code" advice?
> That is also advice.  Generally you use a dict of functions, or some other
> structure to lookup what you want to do.

More specifically, my function looks like this:

def detectMimeType( filename ):

    extension = filename[-3:]
    basename = os.path.basename(filename)

    if extension == "php":
        return "application/x-php"

    elif extension == "cpp" or extension.endswith("cc"):
        return "text/x-c++-src"
# etcetera
    elif extension == "xsl":
        return "text/xsl"

    elif basename.find( "Makefile" ) != -1:
        return "text/x-makefile"
        raise NoMimeError
(don't bother if the MIME detection looks like stone age, it's temporary until 
PyXDG gets support for the XDG mime type spec..)

I'm now wondering if it's possible to write this in a more compact way, such 
that the if-clause isn't necessary? Of course, the current code works, but 
perhaps it could be prettier.

I'm thinking along the lines of nested lists, but what is the obstacle for me 
is that both the test and return statement are simple expressions; not  
functions or a particular data type. Any ideas?



More information about the Python-list mailing list