Refactoring; arbitrary expression in lists

Jeff Shannon jeff at ccvcorp.com
Wed Jan 12 15:42:30 EST 2005


Paul McGuire wrote:

> "Frans Englich" <frans.englich at telia.com> wrote in message
> news:mailman.576.1105553330.22381.python-list at python.org...
>>#--------------------------------------------------------------
>>def detectMimeType( filename ):
>>
>>    extension = filename[-3:]

You might consider using os.path.splitext() here, instead of always 
assuming that the last three characters are the extension.  That way 
you'll be consistent even with extensions like .c, .cc, .h, .gz, etc.

Note that os.path.splitext() does include the extension separator (the 
dot), so that you'll need to test against, e.g., ".php" and ".cpp".

> Since the majority of your tests will be fairly direct 'extension "XYZ"
> means mimetype "aaa/bbb"', this really sounds like a dictionary type
> solution is called for. 

I strongly agree with this.  The vast majority of your cases seem to 
be a direct mapping of extension-string to mimetype-string; using a 
dictionary (i.e. mapping ;) ) for this is ideal.  For those cases 
where you can't key off of an extension string (such as makefiles), 
you can do special-case processing if the dictionary lookup fails.


>     if extension.endswith("cc"):
>         return extToMimeDict["cpp"]

If the intent of this is to catch .cc files, it's easy to add an extra 
entry into the dict to map '.cc' to the same string as '.cpp'.

Jeff Shannon
Technician/Programmer
Credit International




More information about the Python-list mailing list