gomodfile
A pure-Python parser for go.mod and go.work files that returns what golang.org/x/mod/modfile returns, plus the module and semver helpers from x/mod.
import gomodfile
from gomodfile import module, semver
f = gomodfile.parse(open("go.mod", "rb").read())
for r in f.require:
print(r.mod.path, r.mod.version, "indirect" if r.indirect else "")
module.pseudo_version_base("v1.2.4-0.20191109021931-daa7c04131f5") # 'v1.2.3'
semver.compare("v1.2", "v1.10.0") # -1
Why
PyPI has no go.mod parser. Python tools that read go.mod files write their own, usually with regular expressions, and those disagree with the Go toolchain on the cases below.
require x v1.2.3+meta is reported as v1.2.3, and v1.2 as v1.2.0.
// indirect; reason counts as indirect. // Indirect and // indirect // more do not.
- Backtick-quoted paths are rejected.
- A retract rationale comes from the comment above the directive, the trailing comment, or the block's comment.
godebug, ignore and tool directives, block forms, and interpreted strings ("ab").
- Rejections: unterminated blocks,
/* */ comments, a BOM, /v1 path suffixes, a /v2 path with a v1 version.
Measured: python bench/measure.py (Go 1.27.1 with golang.org/x/mod v0.41.0 as the oracle; the real corpus is 352 go.mod files from popular Go repositories, fetched at pinned commits).
go version go1.27.1 darwin/arm64 | golang.org/x/mod v0.41.0
real go.mod (Parse) files= 352 oracle-accepts= 352 accept/reject=352/352 fields=352/352 reject-message=0/0
real go.mod (ParseLax) files= 352 oracle-accepts= 352 accept/reject=352/352 fields=352/352 reject-message=0/0
generated clean (Parse) files= 4000 oracle-accepts= 3910 accept/reject=4000/4000 fields=3910/3910 reject-message=90/90
generated dirty (Parse) files= 4000 oracle-accepts= 2711 accept/reject=4000/4000 fields=2711/2711 reject-message=1289/1289
generated dirty (ParseLax) files= 4000 oracle-accepts= 3153 accept/reject=4000/4000 fields=3153/3153 reject-message=847/847
mutated (Parse) files= 6000 oracle-accepts= 953 accept/reject=6000/6000 fields=953/953 reject-message=5047/5047
mutated (ParseLax) files= 4000 oracle-accepts= 2031 accept/reject=4000/4000 fields=2031/2031 reject-message=1969/1969
generated go.work files= 4000 oracle-accepts= 750 accept/reject=4000/4000 fields=750/750 reject-message=3250/3250
versions (pseudo/semver) cases= 6000 all-values-and-ok=6000/6000 error-message=9122/9122 {'pseudo_version_time: year 0000 (datetime cannot hold it)': 14}
paths (module) cases= 6000 all-values-and-ok=6000/6000 error-message=22570/22570 {}
semver.compare pairs= 2999 agree=2999/2999
The residual on the versions row: Go parses a pseudo-version timestamp with year 0000, and Python's datetime cannot represent it. pseudo_version_time raises InvalidVersionError there. All other fields on those cases agree.
Incumbents checked, with the same oracle and the same corpora:
- scancode-toolkit
packagedcode/go_mod.py (regex and substring based, run unmodified): 26 of 352 real files (7.39%) match on module, require and exclude; 1531 of 3910 accepted generated files (39.16%). It has no replace, retract, tool, godebug or toolchain support. These figures were measured by the research phase that preceded this package, using the harness for that phase. The stored output was re-read here, not re-executed.
- cve-bin-tool
parsers/go.py: read but not run. It reads only require ( blocks, keeps the last path segment, and truncates versions at - and +, so it cannot match modfile on replace, exclude, or single-line require.
- dependabot-core shells out to
go mod edit -json.
Installation
pip install gomodfile
No runtime dependencies. Python 3.11 or newer.
Usage
Parse a go.mod
f = gomodfile.parse(data, "go.mod") # like modfile.Parse
f = gomodfile.parse_lax(data, "go.mod") # like modfile.ParseLax
f.module.mod.path, f.go.version, f.toolchain
f.require # [Require(mod=Version(path, version), indirect, line)]
f.replace # [Replace(old=Version, new=Version, line)]
f.retract # [Retract(low, high, rationale, line)]
parse raises ParseError with every problem found. str(error) is the message Go prints, one per line.
try:
gomodfile.parse("module a.b/m\ngo bad\nfrob\n")
except gomodfile.ParseError as e:
print(e)
# go.mod:2: invalid go version 'bad': must match format 1.23.0
# go.mod:3: unknown directive: frob
Parse a go.work
w = gomodfile.parse_work(data)
[u.path for u in w.use], w.replace, w.go
JSON like go mod edit -json
File.to_dict() and WorkFile.to_dict() return the structure that go mod edit -json and go work edit -json print. The command line does the same:
python -m gomodfile go.mod
python -m gomodfile --work go.work
python -m gomodfile --lax go.mod
Module paths, versions, pseudo-versions
module.check_path("github.com/a/b/v2") # raises InvalidPathError if malformed
module.escape_path("github.com/Azure/Go") # 'github.com/!azure/!go'
module.is_pseudo_version("v0.0.0-20191109021931-daa7c04131f5") # True
module.pseudo_version_time("v0.0.0-20191109021931-daa7c04131f5") # datetime, UTC
semver.canonical("v1") # 'v1.0.0'
Reference
Parsing
| Function |
Description |
parse(data, filename="go.mod") -> File |
Strict parse, modfile.Parse. data is bytes or str. |
parse_lax(data, filename="go.mod") -> File |
modfile.ParseLax: unknown directives skipped; only go, module, retract, require and ignore are read. |
parse_work(data, filename="go.work") -> WorkFile |
modfile.ParseWork. |
is_directory_path(s) -> bool |
Whether a replace target is a directory path. |
File fields: module, go, toolchain, godebug, require, exclude, replace, retract, tool, ignore. Module also has deprecated. Every entry has line, its 1-based source line. WorkFile fields: go, toolchain, godebug, use, replace. All types are dataclasses; Version is a (path, version) named tuple.
gomodfile.module
| Function |
x/mod equivalent |
check_path, check_import_path, check_file_path |
CheckPath, CheckImportPath, CheckFilePath |
check(path, version) |
Check |
split_path_version, check_path_major, match_path_major |
SplitPathVersion, CheckPathMajor, MatchPathMajor |
escape_path, unescape_path, escape_version, unescape_version |
EscapePath, UnescapePath, EscapeVersion, UnescapeVersion |
is_pseudo_version, is_zero_pseudo_version |
IsPseudoVersion, IsZeroPseudoVersion |
pseudo_version_base, pseudo_version_rev, pseudo_version_time |
PseudoVersionBase, PseudoVersionRev, PseudoVersionTime |
pseudo_version(major, older, t, rev) |
PseudoVersion |
canonical_version |
CanonicalVersion |
Errors are InvalidPathError and InvalidVersionError, both subclasses of ModuleError (a ValueError). Messages match Go's.
gomodfile.semver
is_valid, canonical, major, major_minor, prerelease, build, compare, max_version, sort_versions. Go's semver differs from npm's: a leading v is required, v1 and v1.2 are valid, v1.2+build is not, and build metadata is ignored when comparing.
Command line
| Flag |
Description |
--work |
Parse as go.work. |
--lax |
Parse go.mod like ParseLax. |
Exit codes: 0 parsed, 1 rejected (messages on standard error), 2 could not read the file.
How it works
The lexer and statement parser follow modfile/read.go: tokens, whole-line and end-of-line comments, blocks, and the rule that attaches comments to the statement they belong to. Directive handling follows rule.go and work.go, including canonicalization through CanonicalVersion and the path-major check. module and semver are direct ports. The Go tests compare against the real library through a small Go program in scripts/oracle/, so the port is checked, not assumed.
Text is decoded as UTF-8 with surrogateescape, so invalid bytes are accepted where Go accepts them. Unicode predicates use Python's Unicode tables (Python 3.14: Unicode 16), Go 1.27 may use a newer version.
Derived from golang.org/x/mod. Copyright 2009 The Go Authors, BSD-3-Clause; the license is in LICENSE-go, and the derived files carry the Go Authors copyright line in their headers.
Limitations
- Read only. There is no editing or formatting API, and comments are not exposed except through the retract rationale and
Module.deprecated.
ParseWork is compared without ModulePath (x/mod v0.41.0 does not fill it).
- The version fixer callback (
VersionFixer) is not implemented, so retract is not checked against the module path (fixRetract).
- Replace checks assume a POSIX system: a backslash in a directory target is rejected, as
go does on Linux and macOS.
pseudo_version_time cannot represent year 0000.
- No MVS, no go.sum or
h1: hashes, no GOPRIVATE pattern matching.
Compatibility
Run here: Python 3.14.7, macOS arm64, Go 1.27.1, golang.org/x/mod v0.41.0. The CI workflow runs Python 3.11 to 3.14 with Go 1.26. Those versions are not run locally. Other x/mod versions are not compared; a newer x/mod may add directives.
Development
python3 -m venv .venv && .venv/bin/pip install -e '.[dev]'
.venv/bin/python -m pytest -q
.venv/bin/python -m mypy --strict src tests bench
.venv/bin/python bench/measure.py # full agreement table, needs Go and network
.venv/bin/python scripts/capture_fixtures.py # regenerate tests/fixtures/*.json from the oracle
Without Go on PATH the oracle tests skip with a message and the rest pass. Real go.mod files are fetched into .oracle-cache/ (gitignored) from the commits and sha256 listed in tests/real_pins.txt; none are committed.
License
MIT, see LICENSE. Portions derived from golang.org/x/mod are BSD-3-Clause, see LICENSE-go.