Skip to Content
teigeodata
Languages

Python

teigeodata from Python 3.11 and later: offline search, reverse geocoding, admin units, timezones and elevation, with rows as dicts.

The Python package is a native extension (PyO3) over the Rust engine, with type stubs. One abi3 wheel per platform serves CPython 3.11 and later; free-threaded builds (3.14t, 3.15t) get their own wheels and run queries in parallel without the GIL.

Every example on this page ran

The code below is cut from one program, the tour, which CI runs on the released public pack world-np-lite.tgd (data-2026.11.14.3) and checks line by line against the output shown here. The output is the same in every language.

Install

Until the registries are live, build from a checkout (a Rust toolchain is all it needs; rust-toolchain.toml pins the version):

git clone https://github.com/teispace/teigeodata && cd teigeodata
git checkout v1.0.0
PYO3_BUILD_EXTENSION_MODULE=1 cargo build --release -p teigeodata-python --manifest-path bindings/Cargo.toml
cp bindings/target/release/libteigeodata_python.so bindings/python/teigeodata/_native.abi3.so   # .dylib on macOS
export PYTHONPATH=$PWD/bindings/python

Or build a wheel with maturin: pip install ./bindings/python.

Get a pack

Queries read packs: signed, memory-mapped files of places. This guide uses the world lite pack: the world's countries, first-level units and cities of 5,000 or more, India's districts and statutory towns, and Nepal in full, 172,339 places named in Nepali, Hindi and English (15.6 MB, CC BY 4.0):

curl -LO https://github.com/teispace/teigeodata/releases/download/data-2026.11.14.3/world-np-lite.tgd
shasum -a 256 world-np-lite.tgd   # 243ae55509a538b1f61da50994a791cc78e7deb70bb4bf743b9f59d458cbe3f3

An app ships a pack inside its bundle, or downloads one when a user needs it. Once the signed catalog is live, the store does that download for you: it verifies every byte and keeps the packs updated.

Read a result

Every query returns a result blob: the rows as compact columns in one Blob, a buffer the library lends without a copy (memoryview(blob); bytes(blob) copies it), read in place. teigeodata.blob.Reader reads it; iterating gives each row as a dict from column name to value, with None where a value is null:

tour.py
def rows(blob):
    """Each row of a result as a dict: column name to value, None where null."""
    return Reader(blob).records()

For large results read whole columns instead: reader.numbers("lat") is a memoryview of the blob (no copy), reader.strings("name") a list, reader.nulls("elevation") which rows are null, and reader.column("level") one value per row. reader.rows and reader.columns describe the shape. The import:

tour.py
import teigeodata
from teigeodata.blob import Reader

Open a pack

An Engine holds the packs it answers from. open_file memory-maps a pack file and adds it as a layer; the engine answers from every layer at once, and a higher layer wins where two disagree. Opening is cheap: the head of the file is read and checked and the block hashes of large sections are proved; each section is verified against its hash the first time a query reads it.

tour.py
engine = teigeodata.Engine()
engine.open_file(pack)
print("layers:", engine.layers())
Output
layers: 1
  • open_bytes adds a pack from bytes already in memory (a download, an app asset, the browser). open_file_range opens a pack stored uncompressed inside another file, such as an Android APK.
  • Each _with form takes OpenOptions: precedence over the other packs, when sections are verified (lazy, eager or trusted), whether the file is mapped or read, and which components, languages and outline level to read.
  • open_file returns the layer's number; remove takes it out again while other threads keep querying. One engine answers from any number of threads at once.

Search by name

search finds places by name, best first. It matches every name a place has, in every script, and forgives spelling: काठमाडौं, Kathmandu and Kathamandu find the same city, and so do typos, missing accents and abbreviations. A result row has the place columns (id, name, kind, level, lat, lon, elevation, parent, tz, iso, population, population_kind) and a score.

tour.py
for p in rows(engine.search("Pokhara", 3)):
    print(f"{p['id']}  {p['name']}  {p['kind']}  {p['lat']:.4f}, {p['lon']:.4f}  score {p['score']}")
Output
tgd:np/1xhb  Pokhara  settlement  28.2669, 83.9680  score 132
tgd:np/1xnr  Pokhara  admin  28.2094, 83.9818  score 105
tgd:np/15t1  Pokhara  settlement  28.0636, 82.3786  score 90

The score ranks the rows of one query and means nothing across queries. It adds how well the name matched to how important the place is, so a city ranks above a village of the same name. limit is at most 10,000 (LIMIT_MAX).

Narrow a search by its parent

Write the place's parent after a comma, as people do: "Kathmandu, Bagmati". Places inside a unit of that name rank first; the parent can be any ancestor (a district, a province, a country) and is matched with the same tolerance as the name.

tour.py
for p in rows(engine.search("Kathmandu, Bagmati", 2)):
    print(f"{p['id']}  {p['name']}  {p['kind']} {p['level']}")
Output
tgd:np/2cn  Kathmandu  settlement 0
tgd:np/2gm  Kathmandu  admin 3

The city (a settlement, level 0) and the metropolitan municipality (an admin unit at level 3) share the name, and both are in Bagmati.

Rank by distance from a point

Many places share a name. search_with takes SearchOptions: a focus point (the user's location, or the middle of the map they are looking at) ranks near places first. A place at the focus gains 30 points, one focus_scale_m away 15, and the gain keeps halving with distance (the default scale is 50 km).

tour.py
# Many places share a name; a focus (the user's location) ranks the near ones first.
options = teigeodata.SearchOptions(focus_lat=28.7, focus_lon=80.6, focus_scale_m=30_000)
for p in rows(engine.search_with("Shivapur", 3, options)):
    print(f"{p['id']}  {p['name']}  {p['lat']:.4f}, {p['lon']:.4f}")
Output
tgd:np/2v99  Shivapur  28.5310, 80.8213
tgd:np/2raj  Shivapur  28.7141, 80.9869
tgd:np/2rkx  Shivapur  28.5061, 81.3032

Set strict to rank by how well the name matched first (exact, loose, prefix, one edit, substring, two edits, phonetic), then by importance and focus, instead of one combined score: useful for an autocomplete that must show exact matches on top.

Get a place by its ID

Every place has a stable ID such as tgd:np/1xhb: the country, then a short code. IDs survive rebuilds of the data; when two places are merged, get on the retired ID answers with the survivor, so IDs you stored keep working.

tour.py
(place,) = rows(engine.get("tgd:np/1xhb"))
print(place["name"], place["kind"])
print(f"at {place['lat']:.6f}, {place['lon']:.6f}, {place['elevation']} m")
print("timezone", place["tz"], "parent", place["parent"])
Output
Pokhara settlement
at 28.266890, 83.968000, 1006 m
timezone Asia/Kathmandu parent tgd:np/1xnr

elevation is metres above mean sea level (EGM2008), tz the IANA zone and parent the ID of the unit that holds the place. Any column may be null where the data has no value: read each through the reader, which gives your language's null.

Walk the admin hierarchy

ancestors lists the units that hold a place, parent first, up to its country; parent gives the first of them alone and children the units and places one level down.

tour.py
for p in rows(engine.ancestors("tgd:np/1xhb")):
    print(f"{p['kind']} {p['level']}  {p['name']}  {p['iso'] or ''}".rstrip())
children = rows(engine.children("tgd:np/295c"))
print("Kaski has", len(children), "children")
Output
admin 3  Pokhara
admin 2  Kaski
admin 1  Gandaki  NP-P4
country 0  Nepal  NP
Kaski has 5 children

level is the admin level as each country defines it: 0 is a country (and a settlement, which is not a unit), 1 a province or state, and so on down to the lowest level the data has. Each country's ladder is in its profile on the data pages.

Reverse geocode a point

reverse gives the places nearest a point, nearest first, each with meters (the great-circle distance) and bearing (degrees clockwise from north, from the place to the point: "3.2 km at 45° from Pokhara").

tour.py
for p in rows(engine.reverse(27.7172, 85.3240, 3)):
    print(f"{p['name']}  {p['meters']:.0f} m at {p['bearing']:.0f}°")
Output
Narayanhiti Royal Palace  331 m at 116°
Gairidhara  375 m at 220°
Naxal  384 m at 329°

For the admin units that hold a point (its district, province and country) use admin_at below; reverse answers with what is near it.

Find everything within a radius

within_radius gives the places within a distance of a point, nearest first, with the same meters and bearing columns, at most limit of them.

tour.py
within = rows(engine.within_radius(27.7172, 85.3240, 500.0, 10))
print(len(within), "places within 500 m; farthest", f"{within[-1]['meters']:.0f} m")
Output
3 places within 500 m; farthest 384 m

Find places near a place

nearby is reverse geocoding from a place you already have: the places nearest it, itself left out.

tour.py
for p in rows(engine.nearby("tgd:np/2cn", 3)):
    print(f"{p['name']}  {p['meters']:.0f} m")
Output
Bhrikuti Mandap  168 m
Bagbazar  354 m
Shahidgate  393 m

Admin units at a point, and ISO 3166 codes

admin_at tests the point against the admin boundaries and gives every unit that holds it, country first. by_iso finds a country or a subdivision by its ISO 3166 code (NP, NP-P4, in either case).

tour.py
for p in rows(engine.admin_at(28.2096, 83.9856)):
    print(f"{p['level']}  {p['name']}  {p['iso'] or ''}".rstrip())
(state,) = rows(engine.by_iso("NP-P4"))
print("NP-P4 is", state["name"], state["id"])
Output
0  Nepal  NP
1  Gandaki  NP-P4
2  Kaski
3  Pokhara
NP-P4 is Gandaki tgd:np/2922

Boundaries are exact polygons, so a point near a border is answered by the side it is on, not by the nearest centre. Disputed boundaries are drawn from one stated perspective; see accuracy.

Timezones: the zone, its offset and local times

tz_at gives the IANA zone at a point as the zone boundaries draw it. With the zone, tz_offset_at gives the UTC offset at an instant (from the tzdb rules inside the pack, not from the operating system), and tz_local tells whether a wall-clock time exists: unique, gap (skipped by a daylight-saving change) or overlap (it happens twice), with the offsets before and after.

tour.py
(area,) = rows(engine.tz_at(27.7172, 85.3240))
zone = area["tz"]
(offset,) = rows(engine.tz_offset_at(zone, 1_700_000_000))
print(zone, offset["seconds"], "s east of UTC,", offset["abbr"], "dst", offset["dst"])
(local,) = rows(engine.tz_local("America/New_York", 2026, 3, 8, 2, 30, 0))
print("02:30 on 2026-03-08 in New York:", local["kind"], local["before"], "->", local["after"])
print("tzdb", engine.tz_version())
Output
Asia/Kathmandu 20700 s east of UTC, +0545 dst 0
02:30 on 2026-03-08 in New York: gap -18000 -> -14400
tzdb 2026f

tz_version names the tzdb release the rules come from, so you can tell when a pack is older than a rule change; tz_zones lists every zone the packs hold.

Elevation at any point

elevation_at reads the terrain height at a point from the pack's elevation grid, interpolated between the four samples around it: meters above EGM2008, the source product, the grid's resolution_m and the datum. There is no row at sea or outside every grid.

tour.py
(height,) = rows(engine.elevation_at(27.7172, 85.3240))
print(f"{height['meters']:.1f} m above {height['datum']} ({height['source']}, {height['resolution_m']:.0f} m grid)")
Output
1304.2 m above EGM2008 (nasadem, 464 m grid)

Every place also has its own elevation column. The world pack carries a coarse grid; a country's terrain pack adds a finer one, and the engine answers from the finest grid that covers the point.

Distance and bearing

distance_m is the great-circle distance in metres (haversine on the WGS84 mean sphere, within about 0.5% of the ellipsoid), and bearing_deg the initial bearing from the first point to the second, in degrees clockwise from north. Neither needs a pack. Between two places you already have, distance takes their IDs and answers one row with meters and bearing.

tour.py
meters = teigeodata.distance_m(27.7172, 85.3240, 28.2096, 83.9856)
heading = teigeodata.bearing_deg(27.7172, 85.3240, 28.2096, 83.9856)
print(f"Kathmandu to Pokhara: {meters / 1000:.1f} km, heading {heading:.0f}°")
(apart,) = rows(engine.distance("tgd:np/2cn", "tgd:np/1xhb"))
print(f"place to place: {apart['meters'] / 1000:.1f} km at {apart['bearing']:.0f}°")
Output
Kathmandu to Pokhara: 142.4 km, heading 293°
place to place: 146.9 km at 296°

distance answers no row when either ID is unknown. From a point to a place, pass the place's lat and lon to distance_m. The bearing is the direction you set off in: on a great circle it changes along the way, so the bearing back is not the reverse of this one.

A place's outline

boundary answers a unit's outline as one row: geojson, an RFC 7946 Feature (a Polygon or MultiPolygon, outer rings counterclockwise and holes clockwise, seven decimals as stored), with the lod read, its tolerance_m and the number of vertices. A place with no outline answers its point as the geometry; an unknown ID answers no row.

tour.py
(shape,) = rows(engine.boundary("tgd:np/2gm", 0))
feature = json.loads(shape["geojson"])  # a GeoJSON Feature, for any map library
print(f"{feature['geometry']['type']} of {shape['vertices']} vertices at level {shape['lod']}")
print(f"tolerance {shape['tolerance_m']:.0f} m, {len(shape['geojson'])} bytes of GeoJSON")
Output
Polygon of 176 vertices at level 0
tolerance 0 m, 4362 bytes of GeoJSON

The Feature goes to a map as it is: MapLibre's and Leaflet's GeoJSON sources, OpenLayers, Shapely's shape(), Turf and JTS all read it.

  • Level of detail. lod 0 is full resolution; 1 to 6 are coarser, each within its tolerance_m, with neighbouring units still sharing their borders at every level. A pack stored at full resolution only (the lite packs) answers every level as 0. A country at level 0 can be megabytes: draw a coarser level, and keep 0 for measuring.
  • lod above 6 is InvalidArgument; a pack installed without boundaries is MissingComponent.
  • Whether a point is inside a unit is admin_at, which tests the same outlines without building them.

Errors

A call fails with one of eight stable codes, the same in every language:

CodeMeaning
InvalidArgumentAn argument is outside its range: a latitude of 91, a limit over 10,000, a malformed ID.
MissingComponentThe query needs a component the pack was installed without (search on a pack installed without search).
CorruptThe bytes are not a valid pack, or a section does not match its hash.
IoA file could not be read.
NetworkNo mirror answered, or the connection broke (the store only).
RefusedThe store refused: the catalog did not verify, a pack is not installed or another needs it.
CancelledA callback or a job was asked to stop.
InternalA bug inside teigeodata; a panic never crosses into your program.

A query that finds nothing is not an error: it returns no rows.

Each code is an exception class under teigeodata.TeiGeodataError: InvalidArgumentError, MissingComponentError, CorruptError and so on.

tour.py
try:
    engine.reverse(91.0, 0.0, 1)
except teigeodata.InvalidArgumentError as error:
    print("invalid argument:", error)
Output
invalid argument: (91, 0) is not a point: the latitude is outside -90 to 90 degrees

Threads and asyncio

An Engine is safe to share between threads, and queries release the GIL: a thread pool runs them in parallel, and on a free-threaded build so does every thread. The store's long calls (install, update) run as a Job; teigeodata.aio awaits one (await aio.result(job)) and streams its progress (async for done, total in aio.progress(job)).

The whole program

Run it from a checkout of the repository, which builds what the language needs, fetches the pinned pack and compares the output:

cargo xtask docs-examples --fetch --check --lang python

Next

  • Concepts: places and IDs, packs and components, results, the store.
  • Reference: every query, its columns and its errors.
  • Data: what each country's packs hold, with their sources and measured accuracy.

On this page