Python
BGrid for Python
The official Python implementation of the BGrid protocol. Built on the standard library with zero external dependencies, it is suitable for server-side applications, data analysis, scripting, and CLI workflows. Full type hints and dataclass support are included.
Features
- Zero External Dependencies: Uses only the Python standard library.
- Type Hints & Dataclasses: Full type annotations and structured data via
BGridCoordinate. - CLI Tool: Built-in command-line interface for encoding and decoding.
- BIP39 Word Support: Encode and decode grid indices as human-readable words in 5 languages.
- Dual API Style: Object-oriented
BGridclass and convenience module-level functions. - JS-Compatible Helpers: Drop-in equivalents of the JavaScript API for cross-language parity.
Installation
pip install bgrid
Or install from source:
git clone https://github.com/bgrid-maps/bgrid-python.git
cd bgrid-python
pip install -e .
Requirements: Python >= 3.7
Quick Start
from bgrid import BGrid, Language
bgrid = BGrid(load_languages=[Language.ENGLISH])
# Encode coordinates to BGrid
coord = bgrid.dd_to_bgrid(40.7128, -74.0060, level=3)
print(coord.indices) # [531, 1563, 1600]
print(coord.center_lat) # 40.713958...
print(coord.center_lon) # -74.005279...
print(coord.bounds) # ((min_lat, min_lon), (max_lat, max_lon))
# Decode back to coordinates
result = bgrid.bgrid_to_dd([531, 1563, 1600])
print(result['center']) # (lat, lon)
print(result['bounds']) # ((min_lat, min_lon), (max_lat, max_lon))
# Convert to BIP39 words
words = bgrid.indices_to_words([531, 1563, 1600], Language.ENGLISH)
print(words) # ['word1', 'word2', 'word3']
API Reference
Class: BGrid
Constructor
BGrid(load_languages=None, bip39_dir=None)
| Parameter | Type | Default | Description |
|---|---|---|---|
load_languages | List[Language] | [Language.ENGLISH] | Languages to load BIP39 words for |
bip39_dir | str | Path | Bundled wordlists | Directory containing bip39-*.json files |
dd_to_bgrid(lat, lon, level)
Converts decimal degree coordinates to a BGridCoordinate.
dd_to_bgrid(lat: float, lon: float, level: int = 4) -> BGridCoordinate
| Parameter | Type | Description |
|---|---|---|
lat | float | Latitude (-90 to 90) |
lon | float | Longitude (-180 to 180) |
level | int | Hierarchy depth, 1 to 4 |
Returns: BGridCoordinate with indices, center_lat, center_lon, bounds, and level.
Raises: ValueError for invalid coordinates or level.
bgrid_to_dd(indices)
Converts BGrid indices back to geographic coordinates and bounds.
bgrid_to_dd(indices: List[int]) -> dict
| Parameter | Type | Description |
|---|---|---|
indices | List[int] | List of BGrid indices (1–2048) |
Returns: Dict with keys center (tuple), bounds (nested tuple), and level (int).
indices_to_words(indices, language)
Converts BGrid indices to BIP39 words.
indices_to_words(indices: List[int], language: Language = Language.ENGLISH) -> List[str]
| Parameter | Type | Description |
|---|---|---|
indices | List[int] | List of indices (1–2048) |
language | Language | BIP39 language enum value |
Returns: List of word strings.
words_to_indices(words, language)
Converts BIP39 words back to BGrid indices.
words_to_indices(words: List[str], language: Language = Language.ENGLISH) -> List[int]
| Parameter | Type | Description |
|---|---|---|
words | List[str] | List of BIP39 words (case-insensitive) |
language | Language | BIP39 language enum value |
Returns: List of indices (1–2048).
parse_bgrid_string(bgrid_str, language)
Parses a BGrid string (numbers or words) into a BGridCoordinate.
parse_bgrid_string(bgrid_str: str, language: Language = Language.ENGLISH) -> BGridCoordinate
| Parameter | Type | Description |
|---|---|---|
bgrid_str | str | Comma-separated indices or words |
language | Language | Language for word parsing |
Returns: BGridCoordinate object.
get_area_km2(level)
Returns the approximate area of a cell at the given hierarchy level.
get_area_km2(level: int) -> float
| Level | Approximate Area |
|---|---|
| 1 | ~249,023 km² |
| 2 | ~121.6 km² |
| 3 | ~0.059 km² |
| 4 | ~0.000029 km² |
Dataclass: BGridCoordinate
@dataclass
class BGridCoordinate:
indices: List[int]
level: int
center_lat: float
center_lon: float
bounds: Tuple[Tuple[float, float], Tuple[float, float]]
Methods
to_words(language, bgrid)— Convert indices to BIP39 words.to_string(use_words, language, bgrid)— Comma-separated string representation (numbers or words).
Convenience Functions
Module-level functions for quick one-off conversions:
from bgrid import dd_to_bgrid, bgrid_to_dd
# Encode to string
grid_str = dd_to_bgrid(40.7128, -74.0060, level=3) # "531,1563,1600"
grid_words = dd_to_bgrid(40.7128, -74.0060, level=3,
use_words=True, language='en') # "word1,word2,word3"
# Decode from string
lat, lon = bgrid_to_dd("531,1563,1600")
JS-Compatible Helpers
Drop-in equivalents of the JavaScript API for cross-language parity:
from bgrid import coords_to_bgrid, bgrid_to_cell, get_grid_cells, grid_to_display
grid = coords_to_bgrid(40.7128, -74.0060, 3) # [531, 1563, 1600]
cell = bgrid_to_cell(grid) # {"lat": ..., "lon": ..., "bounds": ...}
cells = get_grid_cells(1) # All 2048 level-1 cells
display = grid_to_display(grid, mode="numbers") # "531,1563,1600"
CLI Usage
The library installs a bgrid command-line tool:
# Encode coordinates
bgrid encode 40.7128 -74.0060 --level 3
bgrid encode 40.7128 -74.0060 --level 2 --words --lang es
# Decode BGrid
bgrid decode "531,1563,1600"
bgrid decode "abandon,ability" --lang en
BIP39 Word Support
The library supports 5 languages for BIP39 word encoding:
en, es, fr, pt, zh
Word lists are bundled as JSON files and loaded at initialization via the load_languages constructor parameter, or lazily via load_language().
Language Enum
class Language(Enum):
ENGLISH = 'en'
SPANISH = 'es'
FRENCH = 'fr'
PORTUGUESE = 'pt'
CHINESE = 'zh'
Resources
- Source Code: GitHub Repository
- PyPI: bgrid