Generate a Python module of UN/LOCODE identifiers from the official UNECE release archive.
The generated un_locode.py is intended as a drop-in replacement for the
outdated file shipped with NetBox at
netbox/extras/data/un_locode.py.
The module exposes the same UN_LOCODE tuple of (code, label) pairs, so it
can be swapped in without code changes on the consumer side.
- Python 3.11+ (uses
tomllib, standard library only) - Network access for the first run (downloads the release ZIP and an ISO-3166 country list)
python unlocodegen.pyThe script:
- Reads
config.toml. - Downloads the release ZIP to the configured path if it is not already present, otherwise reuses the local file.
- Extracts the archive into a temporary directory.
- Parses
UNLOCODE Codelist.xmlandSubdivisionCodes.csv. - Fetches an ISO-3166-1 list to resolve country names.
- Writes
build/un_locode.pycontaining a sortedUN_LOCODEtuple of(code, label)pairs in the form('AD-ALV', 'AD-ALV (Andorra la Vella, Andorra)').
Subdivision names are inserted between location and country when the entry has
a <Subdivision> element, e.g. 'ZW-ZMZ (Zimbabwe, Masvingo, Zimbabwe)'.
All configuration lives in config.toml:
| Key | Purpose |
|---|---|
source |
URL of the UNECE release ZIP. |
zip |
Local cache path for the ZIP (relative to repo root). |
input |
XML path inside the extracted archive. |
subdivisions |
Subdivision CSV path inside the extracted archive. |
output |
Destination Python module. |
use_name_wo_diacritics |
When true (default), use <NameWoDiacritics> for location names; falls back to <Name> if missing. |
iso_source |
URL of an ISO-3166-1 CSV used for country names. |
iso_name_columns / iso_code_columns |
Candidate column names in the ISO CSV. |
netbox_unlocode |
URL of the upstream NetBox un_locode.py used by the comparison script. |
To force a fresh download, delete the cached ZIP file before running.
The generated module is plain Python and can be imported directly:
from build.un_locode import UN_LOCODEcompare_netbox.py downloads the current NetBox un_locode.py from the URL
configured as netbox_unlocode in config.toml, parses both
modules and prints a summary plus per-entry diff:
python unlocodegen.py # build build/un_locode.py first
python compare_netbox.pyThe output reports:
- entry counts on both sides
- codes only present in NetBox (i.e. removed upstream of the new release)
- codes only present in the generated build (i.e. new entries)
- entries whose label differs between the two modules
The upstream file is cached at download/netbox_un_locode.py.
Released under the MIT License. Use, modify and redistribute freely; the software is provided as-is, without any warranty or liability.