Skip to content

Fix Marker non-version-to-version comparison throwing InvalidVersion #883

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 11 additions & 2 deletions src/packaging/markers.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
from ._tokenizer import ParserSyntaxError
from .specifiers import InvalidSpecifier, Specifier
from .utils import canonicalize_name
from .version import InvalidVersion, Version

__all__ = [
"InvalidMarker",
Expand Down Expand Up @@ -175,12 +176,20 @@ def _format_marker(


def _eval_op(lhs: str, op: Op, rhs: str) -> bool:
# PEP 508 - Environment Markers
# https://peps.python.org/pep-0508/#environment-markers
# > The <version_cmp> operators use the PEP 440 version comparison rules
# > when those are defined (that is when both sides have a valid version
# > specifier). If there is no defined PEP 440 behaviour and the operator
# > exists in Python, then the operator falls back to the Python behaviour.
# > Otherwise an error should be raised.
try:
spec = Specifier("".join([op.serialize(), rhs]))
except InvalidSpecifier:
lhs_ver = Version(lhs)
except (InvalidSpecifier, InvalidVersion):
pass
else:
return spec.contains(lhs, prereleases=True)
return spec.contains(lhs_ver, prereleases=True)

oper: Operator | None = _operators.get(op.serialize())
if oper is None:
Expand Down
8 changes: 8 additions & 0 deletions tests/test_markers.py
Original file line number Diff line number Diff line change
Expand Up @@ -314,6 +314,14 @@ def test_environment_with_extra_none(self):
{"extra": "different__punctuation_is_EQUAL"},
True,
),
# extra name that is also a valid version - version comparison applies
# if both sides are valid versions
("extra == 'v8'", {"extra": "quux"}, False),
("extra == 'v8'", {"extra": "v8"}, True),
# LHS and RHS are valid versions, so equality uses normalized version
("extra == 'v8-dev'", {"extra": "v8-dev.0"}, True),
# LHS and RHS are not valid versions, so equality is str comparison
("extra == 'v8-foo'", {"extra": "v8-foo.0"}, False),
],
)
def test_evaluates(self, marker_string, environment, expected):
Expand Down