Skip to content

About

npm's node-semver versions and ranges in pure Python, checked against node-semver's own fixtures.

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Latest commit

 

History

2 Commits

Folders and files

Repository files navigation

npm-semver

Pure-Python implementation of npm's node-semver versions and ranges, checked against node-semver's own fixtures and against the real package.

import npm_semver as semver

semver.satisfies("1.2.4", "^1.2.3")                 # True
semver.valid_range("~1.2 || 3.x")                   # '>=1.2.0 <1.3.0-0||>=3.0.0 <4.0.0-0'
semver.max_satisfying(["1.2.3", "1.9.0", "2.0.0"], "^1.2.0")   # '1.9.0'
semver.satisfies("1.2.4-beta", "^1.2.3")            # False (prerelease tuple rule)
semver.inc("1.2.3", "prerelease", None, "beta")     # '1.2.4-beta.0'
semver.coerce("v2.3 of the docs").version           # '2.3.0'

Why

Python has PEP 440 (packaging) and strict SemVer (python-semver). npm ranges are a different grammar: ^ and ~ on 0.x, x-ranges, hyphen partials, ||, the rule that a prerelease only matches a range that names a prerelease on the same major.minor.patch, and a loose mode that accepts ~=, v prefixes and 1.2.3beta. Tools that read package.json, lockfiles or advisory data need those semantics exactly.

The Python libraries that touch npm ranges were scored against node-semver's own range fixtures (tag v7.8.5, commit 6e05b76). "core" is range-include, range-exclude and range-parse (accepted or rejected). A row is "with options" when it sets loose or includePrerelease. An exception counts as a failure. A library with no option for a row runs it without.

Package (latest release) core, no options core, with options gtr/ltr rows
npm-semver 289/289 = 100.0% 68/68 = 100.0% 277/277
node-semver 0.9.1 (2026-06) 269/289 = 93.1% 65/68 = 95.6% 169/277 = 61.0% (outside raises TypeError)
univers 32.0.1 (2026-05), NpmVersionRange 213/289 = 73.7% 41/68 = 60.3% no such function
semantic-version 2.10.0 (2022-05), NpmSpec 209/289 = 72.3% 28/68 = 41.2% no such function
semver_range 0.0.3 (2019-09) 95/289 = 32.9% 17/68 = 25.0% no such function
python-semver 3.1.0, Version.match 30/289 = 10.4% 4/68 = 5.9% no such function

node-semver on PyPI installs the module nodesemver. packaging implements PEP 440, not npm ranges, and was not scored. poetry-semver 0.1.0 (poetry's constraint syntax, not npm's) scores 222/289 and 43/68. None of these has intersects, subset, coerce, min_version or the inc identifier options as node-semver defines them.

Measured: python bench/incumbents.py node-semver (one virtualenv per package; see the script header).

node-semver        core     no options: 269/289 = 93.1%  with options: 65/68 = 95.6%
node-semver        gtr/ltr  no options: 159/256 = 62.1%  with options: 10/21 = 47.6%

Installation

pip install npm-semver

No runtime dependencies. Python 3.11 or later.

Usage

Versions

v = semver.SemVer("v1.2.3-alpha.1+build.5")
v.major, v.minor, v.patch      # 1 2 3
v.prerelease, v.build          # ['alpha', 1] ['build', '5']
str(v)                         # '1.2.3-alpha.1'  (build metadata is not part of .version)

semver.parse("nope")           # None
semver.parse("nope", throw_errors=True)   # raises InvalidVersion
semver.valid("v1.2.3-01", True)           # '1.2.3-1'  (loose)
semver.clean("  =v1.2.3  ")               # '1.2.3'

Comparing and sorting

semver.compare("1.2.3+a", "1.2.3+b")          # 0   (build metadata is ignored)
semver.compare_build("1.2.3+a", "1.2.3+b")    # -1
semver.sort(["1.10.0", "1.2.0", "1.2.0-beta"])   # ['1.2.0-beta', '1.2.0', '1.10.0']
semver.diff("1.2.3", "1.2.4-beta")            # 'prepatch'

Ranges

semver.valid_range("^1.2.x")               # '>=1.2.0 <2.0.0-0'
semver.min_version(">1.0.0-beta")          # SemVer 1.0.0-beta.0
semver.intersects(">=1 <2", ">=1.5 <3")    # True
semver.subset("1.2.3", "^1.0.0")           # True
semver.gtr("2.0.0", "^1.2.3")              # True
semver.to_comparators("^1.2.3 || >2")      # [['>=1.2.3', '<2.0.0-0'], ['>=3.0.0']]

Options

from npm_semver import Options

semver.satisfies("1.2.3-beta", "^1.2.3-alpha", Options(include_prerelease=True))
semver.valid_range("~=1.2.3", Options(loose=True))
semver.coerce("1.2.3.4", Options(rtl=True)).version    # '2.3.4'

Increments

semver.inc("1.2.3", "minor")                                 # '1.3.0'
semver.inc("1.2.3", "prerelease", None, "beta", "1")         # '1.2.4-beta.1'
semver.inc("1.2.3", "prerelease", None, "beta", False)       # '1.2.4-beta'
semver.inc("1.2.3", "prerelease", "beta")                    # a string in the options slot is the identifier

Reference

Every function takes an optional options argument last: None, True (loose), or an Options.

Options field Type Default Description
loose bool False Accept v/= prefixes, leading zeros and 1.2.3beta; drop invalid comparators inside a range.
include_prerelease bool False Let prereleases match any range and lower x-range bounds to -0.
rtl bool False Only read by coerce: pick the right-most version-like run.
Function Returns Notes
parse(v, options, throw_errors=False) SemVer | None
valid(v), clean(v) str | None
major, minor, patch int Raise on invalid input.
prerelease(v) list[int | str] | None
compare, rcompare, compare_build, compare_loose int
gt, gte, lt, lte, eq, neq, cmp(a, op, b) bool
sort, rsort list New list, ordered by precedence then build metadata.
diff(a, b) str | None major, premajor, minor, preminor, patch, prepatch, prerelease.
inc(v, release, options, identifier, identifier_base) str | None release: major premajor minor preminor patch prepatch prerelease release. identifier_base: 0/1 (or "0"/"1"), or False for no counter.
truncate(v, release) str | None
coerce(v, options) SemVer | None Accepts numbers.
satisfies(v, range) bool Invalid input gives False.
max_satisfying, min_satisfying str | SemVer | None
min_version(range) SemVer | None
valid_range(range) str | None Canonical form; "*" for any version.
intersects(a, b), subset(sub, dom) bool
outside, gtr, ltr bool
to_comparators(range) list[list[str]]
simplify_range(versions, range) str | Range Returns range unchanged when the result would not be shorter.

Classes: SemVer (mutable; inc changes it in place), Range (.set, .raw, .range, .test(v), .intersects(r)), Comparator (.operator, .semver, .value, .test(v); .semver is None for the match-anything comparator).

Errors: InvalidVersion and InvalidRange derive from ValueError. Non-string input raises TypeError. Functions that return None or False for bad input in node-semver do the same here.

How it works

The token regular expressions, the range rewriting passes (hyphen, comparator trim, tilde, caret, x-range, star) and the comparator logic follow node-semver 7.8.5 step by step, so behavior matches including its corners:

  • Regexes are built from the same token sources, with the same bounded-quantifier rewrite (\d{0,256}) node-semver applies. JavaScript \s and String.trim use a different whitespace set than Python; the same set is reproduced (for example  is whitespace, \x85 is not).
  • Range arithmetic (^1.2.x upper bound) is done as JavaScript doubles and printed as JavaScript prints numbers, so ^9007199254740990.x and 30-digit majors behave as they do in node.
  • Number(x) semantics for identifier_base and for the isNaN check in prerelease increments ("1e5" and "0x10" count as numbers).
  • Parsed comparator lists are cached in a 1000-entry LRU keyed like node-semver's. subset compares list identity, so the cache is observable and is reproduced.

Ported logic keeps node-semver's ISC notice: see LICENSE-node-semver.

Limitations

  • Behavior is pinned to node-semver 7.8.5. Other versions are untested.
  • sort, rsort and simplify_range return new lists instead of sorting the argument in place.
  • JavaScript null and undefined are not distinguished. None is undefined.
  • Only str, SemVer, and (for coerce) int/float inputs are modeled. JavaScript objects with toString are not accepted.
  • Range(comparator) takes its options from the argument, not from the comparator.
  • No CLI.

Compatibility

Run here: Python 3.14.7 and 3.12.14 on macOS, with Node 24 and semver 7.8.5 as the reference. The CI workflow runs Python 3.11 to 3.14 on Linux; 3.11 and 3.13 have not been run by the author.

Development

python3 -m venv .venv && .venv/bin/pip install -e '.[dev]'
.venv/bin/python -m pytest -rs
.venv/bin/python -m mypy --strict src tests bench

Tests fetch node-semver's fixtures (15 files, 982 rows) from a pinned commit and [email protected] from npm into .fixtures/ (gitignored), verifying sha256 and the npm integrity hash. Without node and npm the fixture and differential tests skip with a message and the rest run.

The differential test (tests/test_differential.py) generates random versions, ranges and options (tests/diff_gen.py), runs them through tests/diff_helper.js against real semver, and compares results. It covers 32 call shapes across 30 functions. Set NPM_SEMVER_SEEDS (default 1,2,3) and NPM_SEMVER_CASES (default 20000) to change the run.

License

MIT, see LICENSE. Portions are adapted from node-semver (ISC), see LICENSE-node-semver.

About

npm's node-semver versions and ranges in pure Python, checked against node-semver's own fixtures.

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages