or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

tessl/pypi-maxminddb

Reader for the MaxMind DB format

Workspace
tessl
Visibility
Public
Created
Last updated
Describes
pypipkg:pypi/maxminddb@2.8.x

To install, run

npx @tessl/cli install tessl/pypi-maxminddb@2.8.0

0

# MaxMind DB Reader

1

2

A high-performance Python reader for MaxMind DB files, which are binary database files that store data indexed by IP address subnets (IPv4 or IPv6). The library includes both a pure Python implementation and an optional C extension for enhanced performance, supporting multiple reading modes including memory mapping, file-based access, and in-memory loading.

3

4

## Package Information

5

6

- **Package Name**: maxminddb

7

- **Language**: Python

8

- **Installation**: `pip install maxminddb`

9

10

## Core Imports

11

12

```python

13

import maxminddb

14

```

15

16

For accessing specific components:

17

18

```python

19

from maxminddb import open_database, Reader, InvalidDatabaseError

20

from maxminddb import MODE_AUTO, MODE_MMAP, MODE_FILE, MODE_MEMORY, MODE_FD, MODE_MMAP_EXT

21

```

22

23

## Basic Usage

24

25

```python

26

import maxminddb

27

28

# Open a MaxMind DB file

29

with maxminddb.open_database('/path/to/GeoIP2-City.mmdb') as reader:

30

# Look up an IP address

31

response = reader.get('128.101.101.101')

32

print(response['country']['iso_code']) # Example: 'US'

33

34

# Get response with network prefix length

35

response, prefix_len = reader.get_with_prefix_len('128.101.101.101')

36

print(f"Network: {response}, Prefix: {prefix_len}")

37

38

# Access database metadata

39

metadata = reader.metadata()

40

print(f"Database type: {metadata.database_type}")

41

print(f"Build time: {metadata.build_epoch}")

42

```

43

44

## Architecture

45

46

MaxMind DB uses a binary tree structure for efficient IP address lookups:

47

48

- **Binary Tree Search**: IP addresses are searched through a binary tree structure where each bit of the IP determines the path

49

- **Data Section**: Contains the actual records referenced by tree nodes

50

- **Multiple Implementations**: Pure Python implementation with optional C extension for performance

51

- **Memory Modes**: Different access patterns (memory mapping, file I/O, full memory load) for various use cases

52

53

## Capabilities

54

55

### Database Opening

56

57

Opens MaxMind DB files with configurable access modes for different performance and memory usage characteristics.

58

59

```python { .api }

60

def open_database(

61

database: str | int | os.PathLike | IO,

62

mode: int = MODE_AUTO

63

) -> Reader:

64

"""

65

Open a MaxMind DB database.

66

67

Parameters:

68

- database: Path to MaxMind DB file, or file descriptor for MODE_FD

69

- mode: Database access mode (see Mode Constants)

70

71

Returns:

72

Reader: Database reader instance

73

74

Raises:

75

ValueError: If unsupported mode specified

76

InvalidDatabaseError: If file is not a valid MaxMind DB

77

"""

78

```

79

80

### IP Address Lookups

81

82

Core functionality for retrieving data associated with IP addresses from the database.

83

84

```python { .api }

85

class Reader:

86

"""Reader for MaxMind DB files with IP lookup capabilities."""

87

88

closed: bool # Indicates whether the database has been closed

89

90

def __init__(

91

self,

92

database: str | int | os.PathLike | IO,

93

mode: int = MODE_AUTO

94

):

95

"""

96

Initialize MaxMind DB reader.

97

98

Parameters:

99

- database: Path to MaxMind DB file, or file descriptor for MODE_FD

100

- mode: Database access mode

101

"""

102

103

def get(self, ip_address: str | IPv4Address | IPv6Address) -> Record | None:

104

"""

105

Return the record for the IP address.

106

107

Parameters:

108

- ip_address: IP address in string notation or ipaddress object

109

110

Returns:

111

Record | None: Database record or None if not found

112

113

Raises:

114

TypeError: If ip_address is not string or ipaddress object

115

ValueError: If IPv6 address used with IPv4-only database

116

"""

117

118

def get_with_prefix_len(

119

self,

120

ip_address: str | IPv4Address | IPv6Address

121

) -> tuple[Record | None, int]:

122

"""

123

Return record with associated network prefix length.

124

125

Parameters:

126

- ip_address: IP address in string notation or ipaddress object

127

128

Returns:

129

tuple[Record | None, int]: (record, prefix_length)

130

"""

131

132

def metadata(self) -> Metadata:

133

"""

134

Return database metadata.

135

136

Returns:

137

Metadata: Database metadata object

138

"""

139

140

def close(self) -> None:

141

"""Close database and release resources."""

142

143

def __enter__(self) -> Reader:

144

"""Context manager entry."""

145

146

def __exit__(self, *args) -> None:

147

"""Context manager exit with automatic cleanup."""

148

149

def __iter__(self) -> Iterator[tuple[ipaddress.IPv4Network | ipaddress.IPv6Network, Record]]:

150

"""

151

Iterate over all database records.

152

153

Yields:

154

tuple: (network, record) pairs for all entries

155

"""

156

```

157

158

### Database Metadata

159

160

Access to comprehensive database metadata including format version, build information, and structural details.

161

162

```python { .api }

163

class Metadata:

164

"""Container for MaxMind DB metadata information."""

165

166

def __init__(self, **kwargs):

167

"""Create Metadata object from database metadata."""

168

169

# Core metadata attributes

170

binary_format_major_version: int # Major version of binary format

171

binary_format_minor_version: int # Minor version of binary format

172

build_epoch: int # Unix timestamp of database build

173

database_type: str # Database type identifier (e.g., "GeoIP2-City")

174

description: dict[str, str] # Locale-to-description mapping

175

ip_version: int # IP version (4 or 6)

176

languages: list[str] # Supported locale codes

177

node_count: int # Number of nodes in search tree

178

record_size: int # Bit size of tree records

179

180

@property

181

def node_byte_size(self) -> int:

182

"""Size of a node in bytes."""

183

184

@property

185

def search_tree_size(self) -> int:

186

"""Size of the search tree in bytes."""

187

```

188

189

### Mode Constants

190

191

Database access mode constants that control how the database file is read and cached.

192

193

```python { .api }

194

# Database access modes

195

MODE_AUTO: int # Auto-select best available mode (default)

196

MODE_MMAP_EXT: int # Memory mapping with C extension (fastest)

197

MODE_MMAP: int # Memory mapping, pure Python

198

MODE_FILE: int # Standard file I/O, pure Python

199

MODE_MEMORY: int # Load entire database into memory, pure Python

200

MODE_FD: int # Read from file descriptor, pure Python

201

```

202

203

### Exception Handling

204

205

Error handling for database-related operations and invalid data conditions.

206

207

```python { .api }

208

class InvalidDatabaseError(RuntimeError):

209

"""

210

Exception raised when invalid or corrupt database data is encountered.

211

212

This includes cases where:

213

- File is not a valid MaxMind DB format

214

- Database metadata is corrupt or unreadable

215

- Search tree contains invalid node data

216

"""

217

```

218

219

## Types

220

221

```python { .api }

222

# Type aliases for database records

223

from typing import Union, AnyStr

224

225

Primitive = Union[AnyStr, bool, float, int]

226

Record = Union[Primitive, "RecordList", "RecordDict"]

227

228

class RecordList(list[Record]):

229

"""List container for database record arrays."""

230

231

class RecordDict(dict[str, Record]):

232

"""Dictionary container for database record objects."""

233

```

234

235

## Advanced Usage Examples

236

237

### Working with Different Database Modes

238

239

```python

240

import maxminddb

241

242

# Memory mapping (fastest for repeated lookups)

243

reader = maxminddb.open_database('/path/to/db.mmdb', maxminddb.MODE_MMAP)

244

245

# File I/O (lowest memory usage)

246

reader = maxminddb.open_database('/path/to/db.mmdb', maxminddb.MODE_FILE)

247

248

# Load into memory (fastest for small databases)

249

reader = maxminddb.open_database('/path/to/db.mmdb', maxminddb.MODE_MEMORY)

250

251

# Using file descriptor

252

with open('/path/to/db.mmdb', 'rb') as f:

253

reader = maxminddb.open_database(f, maxminddb.MODE_FD)

254

```

255

256

### Iterating Over All Records

257

258

```python

259

import maxminddb

260

261

with maxminddb.open_database('/path/to/db.mmdb') as reader:

262

# Iterate over all network/record pairs

263

for network, record in reader:

264

print(f"Network: {network}, Data: {record}")

265

# Process each record as needed

266

```

267

268

### Error Handling

269

270

```python

271

import maxminddb

272

from maxminddb import InvalidDatabaseError

273

274

try:

275

reader = maxminddb.open_database('/path/to/db.mmdb')

276

result = reader.get('192.168.1.1')

277

except InvalidDatabaseError as e:

278

print(f"Database error: {e}")

279

except ValueError as e:

280

print(f"Invalid input: {e}")

281

except FileNotFoundError:

282

print("Database file not found")

283

finally:

284

if 'reader' in locals():

285

reader.close()

286

```

287

288

### Metadata Inspection

289

290

```python

291

import maxminddb

292

from datetime import datetime

293

294

with maxminddb.open_database('/path/to/db.mmdb') as reader:

295

metadata = reader.metadata()

296

297

print(f"Database: {metadata.database_type}")

298

print(f"IP Version: IPv{metadata.ip_version}")

299

print(f"Languages: {', '.join(metadata.languages)}")

300

print(f"Build Date: {datetime.fromtimestamp(metadata.build_epoch)}")

301

print(f"Node Count: {metadata.node_count:,}")

302

print(f"Record Size: {metadata.record_size} bits")

303

304

# Access description in different languages

305

for locale, desc in metadata.description.items():

306

print(f"Description ({locale}): {desc}")

307

```