Skip to content
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__ = [
"EvaluateContext",
Expand Down Expand Up @@ -179,12 +180,20 @@ def _format_marker(

def _eval_op(lhs: str, op: Op, rhs: str | AbstractSet[str]) -> bool:
if isinstance(rhs, str):
# 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
17 changes: 17 additions & 0 deletions tests/test_markers.py
Original file line number Diff line number Diff line change
Expand Up @@ -314,6 +314,23 @@ 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),
#
# When using order comparisons, fallback to str when one or both are
# not valid versions can have counter-intuitive results.
#
# The gentoo value is not a valid version, lexicographic str
# comparison applies. This is True because '6' >= '2'.
("platform_release >= '20'", {"platform_release": "6.7.0-gentoo"}, True),
# Whereas this is False because the gentoo value IS a valid version
("platform_release >= '20'", {"platform_release": "6.7.0+gentoo"}, False),
],
)
def test_evaluates(self, marker_string, environment, expected):
Expand Down