import pkg_resources


def matches_version_range(version, version_range, name=None):
    """Return whether a version matches a given range.

    This will compare the version to a range specification, checking if it
    matches. The range must be in the form of ``name[>=]specifier``.

    If ``name`` is specified, then the name will be compared to the one
    listed in the version range as well.

    Args:
        version (unicode):
            The version to compare against the range.

        version_range (unicode):
            The version range.

        name (unicode, optional):
            The optional name to compare against the one in the version
            range.

    Returns:
        bool:
        ``True`` if the version and, optionally, the name matches.
    """
    req = pkg_resources.Requirement.parse(version_range)

    if name and req.project_name != name:
        return False

    return len(list(req.specifier.filter([version]))) > 0