def select_content_type(requested, available):
class Match(object):<EOL><INDENT>"""<STR_LIT>"""<EOL>WILDCARD, PARTIAL, FULL_TYPE, = <NUM_LIT:2>, <NUM_LIT:1>, <NUM_LIT:0><EOL>def __init__(self, candidate, pattern):<EOL><INDENT>self.candidate = candidate<EOL>self.pattern = pattern<EOL>if pattern.content_type == pattern.content_subtype == '<STR_LIT:*>':<EOL><INDENT>self.match_type = self.WILDCARD<EOL><DEDENT>elif pattern.content_subtype == '<STR_LIT:*>':<EOL><INDENT>self.match_type = self.PARTIAL<EOL><DEDENT>else:<EOL><INDENT>self.match_type = self.FULL_TYPE<EOL><DEDENT>self.parameter_distance = len(self.candidate.parameters)<EOL>for key, value in candidate.parameters.items():<EOL><INDENT>if key in pattern.parameters:<EOL><INDENT>if pattern.parameters[key] == value:<EOL><INDENT>self.parameter_distance -= <NUM_LIT:1><EOL><DEDENT>else:<EOL><INDENT>self.parameter_distance += <NUM_LIT:1><EOL><DEDENT><DEDENT><DEDENT><DEDENT><DEDENT>def extract_quality(obj):<EOL><INDENT>return getattr(obj, '<STR_LIT>', <NUM_LIT:1.0>)<EOL><DEDENT>matches = []<EOL>for pattern in sorted(requested, key=extract_quality, reverse=True):<EOL><INDENT>for candidate in sorted(available):<EOL><INDENT>if _content_type_matches(candidate, pattern):<EOL><INDENT>if candidate == pattern:  <EOL><INDENT>if extract_quality(pattern) == <NUM_LIT:0.0>:<EOL><INDENT>raise errors.NoMatch  <EOL><DEDENT>return candidate, pattern<EOL><DEDENT>matches.append(Match(candidate, pattern))<EOL><DEDENT><DEDENT><DEDENT>if not matches:<EOL><INDENT>raise errors.NoMatch<EOL><DEDENT>matches = sorted(matches,<EOL>key=attrgetter('<STR_LIT>', '<STR_LIT>'))<EOL>return matches[<NUM_LIT:0>].candidate, matches[<NUM_LIT:0>].pattern<EOL>
Selects the best content type.

    :param requested: a sequence of :class:`.ContentType` instances
    :param available: a sequence of :class:`.ContentType` instances
        that the server is capable of producing

    :returns: the selected content type (from ``available``) and the
        pattern that it matched (from ``requested``)
    :rtype: :class:`tuple` of :class:`.ContentType` instances
    :raises: :class:`.NoMatch` when a suitable match was not found

    This function implements the *Proactive Content Negotiation*
    algorithm as described in sections 3.4.1 and 5.3 of :rfc:`7231`.
    The input is the `Accept`_ header as parsed by
    :func:`.parse_http_accept_header` and a list of
    parsed :class:`.ContentType` instances.  The ``available`` sequence
    should be a sequence of content types that the server is capable of
    producing.  The selected value should ultimately be used as the
    `Content-Type`_ header in the generated response.

    .. _Accept: http://tools.ietf.org/html/rfc7231#section-5.3.2
    .. _Content-Type: http://tools.ietf.org/html/rfc7231#section-3.1.1.5