Refactoring; arbitrary expression in lists
Stephen Thorne
stephen.thorne at gmail.com
Wed Jan 12 21:19:06 EST 2005
On Thu, 13 Jan 2005 01:24:29 GMT, Bengt Richter <bokr at oz.net> wrote:
> extensiondict = dict(
> php = 'application/x-php',
> cpp = 'text/x-c-src',
> # etcetera
> xsl = 'test/xsl'
> )
>
> def detectMimeType(filename):
> extension = os.path.splitext(filename)[1].replace('.', '')
> try: return extensiondict[extension]
> except KeyError:
> basename = os.path.basename(filename)
> if "Makefile" in basename: return 'text/x-makefile' # XXX case sensitivity?
> raise NoMimeError
Why not use a regexp based approach.
extensionlist = [
(re.compile(r'.*\.php') , "application/x-crap-language"),
(re.compile(r'.*\.(cpp|c)') , 'text/x-c-src'),
(re.compile(r'[Mm]akefile') , 'text/x-makefile'),
]
for regexp, mimetype in extensionlist:
if regexp.match(filename):
return mimetype
if you were really concerned about efficiency, you could use something like:
class SimpleMatch:
def __init__(self, pattern): self.pattern = pattern
def match(self, subject): return subject[-len(self.pattern):] == self.pattern
Regards,
Stephen Thorne
More information about the Python-list
mailing list