Skip to content

Commit 5443249

Browse files
committed
cleaner code for quality_and_fitness_parsed
1 parent c1e74a7 commit 5443249

File tree

2 files changed

+34
-15
lines changed

2 files changed

+34
-15
lines changed

mimeparse.py

Lines changed: 33 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -80,22 +80,37 @@ def quality_and_fitness_parsed(mime_type, parsed_ranges):
8080
"""
8181
best_fitness = -1
8282
best_fit_q = 0
83-
(target_type, target_subtype, target_params) =\
83+
(target_type, target_subtype, target_params) = \
8484
parse_media_range(mime_type)
85+
8586
for (type, subtype, params) in parsed_ranges:
86-
type_match = (type == target_type or
87-
type == '*' or
88-
target_type == '*')
89-
subtype_match = (subtype == target_subtype or
90-
subtype == '*' or
91-
target_subtype == '*')
87+
88+
# check if the type and the subtype match
89+
type_match = (
90+
type in (target_type, '*') or
91+
target_type == '*'
92+
)
93+
subtype_match = (
94+
subtype in (target_subtype, '*') or
95+
target_subtype == '*'
96+
)
97+
98+
# if they do, assess the "fitness" of this mime_type
9299
if type_match and subtype_match:
93-
param_matches = reduce(lambda x, y: x + y, [1 for (key, value) in
94-
target_params.items() if key != 'q' and
95-
key in params and value == params[key]], 0)
96-
fitness = (type == target_type) and 100 or 0
97-
fitness += (subtype == target_subtype) and 10 or 0
100+
101+
# 100 points if the type matches w/o a wildcard
102+
fitness = type == target_type and 100 or 0
103+
104+
# 10 points if the subtype matches w/o a wildcard
105+
fitness += subtype == target_subtype and 10 or 0
106+
107+
# 1 bonus point for each matching param besides "q"
108+
param_matches = sum([
109+
1 for (key, value) in target_params.items()
110+
if key != 'q' and key in params and value == params[key]
111+
])
98112
fitness += param_matches
113+
99114
if fitness > best_fitness:
100115
best_fitness = fitness
101116
best_fit_q = params['q']
@@ -156,15 +171,19 @@ def best_match(supported, header):
156171
weighted_matches = []
157172
pos = 0
158173
for mime_type in supported:
159-
weighted_matches.append((quality_and_fitness_parsed(mime_type,
160-
parsed_header), pos, mime_type))
174+
weighted_matches.append((
175+
quality_and_fitness_parsed(mime_type, parsed_header),
176+
pos,
177+
mime_type
178+
))
161179
pos += 1
162180
weighted_matches.sort()
163181

164182
return weighted_matches[-1][0][0] and weighted_matches[-1][2] or ''
165183

166184

167185
def _filter_blank(i):
186+
"""Return all non-empty items in the list."""
168187
for s in i:
169188
if s.strip():
170189
yield s

testdata.json

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -88,7 +88,7 @@
8888
[
8989
[
9090
["application/xbel+xml", "application/xml"],
91-
"*/*", "application/xml"
91+
"*/*"
9292
],
9393
"application/xml",
9494
"match using a type wildcard"

0 commit comments

Comments
 (0)