Re: Refactoring; arbitrary expression in lists

From: Jeff Shannon (jeff_at_ccvcorp.com)
Date: 01/12/05


Date: Wed, 12 Jan 2005 12:42:30 -0800

Paul McGuire wrote:

> "Frans Englich" <frans.englich@telia.com> wrote in message
> news:mailman.576.1105553330.22381.python-list@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



Relevant Pages

  • Re: Can drivers lie?
    ... the implementation is non-conformant. ... if the version says x but an extension string is returned in the ... strings then you dont have that feature on your implementation. ...
    (comp.graphics.api.opengl)
  • Re: Get file extension formula
    ... Microsoft MVP - Excel ... | formula to return the extension string itself? ... | Would want this to fail gracefully if there is no extension and handle ...
    (microsoft.public.excel.programming)