MaxMind DB Python Module

Description

This is a Python module for reading MaxMind DB files. The module includes both a pure Python reader and an optional C extension.

MaxMind DB is a binary file format that stores data indexed by IP address subnets (IPv4 or IPv6).

Installation

To install maxminddb, type:

$ pip install maxminddb

If you are not able to install from PyPI, you may also use pip from the source directory:

$ python -m pip install .

The installer will attempt to build the C extension. If this fails, the module will fall-back to the pure Python implementation.

Usage

To use this module, you must first download or create a MaxMind DB file. We provide free GeoLite databases. These files must be decompressed with gunzip.

After you have obtained a database and imported the module, call open_database with a path, or binary file object (with Mode.FD or Mode.AUTO), to the database as the first argument. Optionally, you may pass a mode as the second argument. The modes are available from maxminddb.Mode. Valid modes are:

  • Mode.MMAP_EXT - use the C extension with memory map.

  • Mode.MMAP - read from memory map. Pure Python.

  • Mode.FILE - read database as standard file. Pure Python.

  • Mode.MEMORY - load database into memory. Pure Python.

  • Mode.FD - load database into memory from a binary file object. Pure Python.

  • Mode.AUTO - try Mode.MMAP_EXT, Mode.MMAP, Mode.FILE in that order. A file object is read into memory with the pure Python reader, as with Mode.FD. Pass a path to use the faster C extension. Default.

NOTE: When using a file object, it is the caller’s responsibility to be sure that the file object gets closed properly. The caller may close the file object immediately after the Reader object is created. The pure Python reader closes a file descriptor that you pass to it. This includes Mode.AUTO when the C extension is not installed.

The open_database function returns a Reader object. To look up an IP address, use the get method on this object. The method will return the corresponding values for the IP address from the database (e.g., a dictionary for GeoIP/GeoLite databases). If the database does not contain a record for that IP address, the method will return None.

If you wish to also retrieve the prefix length for the record, use the get_with_prefix_len method. This returns a tuple containing the record followed by the network prefix length associated with the record.

You may also iterate over the whole database. The Reader class implements the __iter__ method that returns an iterator. This iterator yields a tuple containing the network and the record.

Example

>>> import maxminddb
>>>
>>> with maxminddb.open_database('GeoLite2-City.mmdb') as reader:
>>>
>>>     reader.get('152.216.7.110')
{'country': ... }
>>>
>>>     reader.get_with_prefix_len('152.216.7.110')
({'country': ... }, 24)
>>>
>>>     for network, record in reader:
>>>         ...

Exceptions

The module will return an InvalidDatabaseError if the database is corrupt or otherwise invalid. A ValueError will be thrown if you look up an invalid IP address or an IPv6 address in an IPv4 database.

The reader also raises InvalidDatabaseError when one record, or the database metadata, exceeds its resource limits: 65,536 decoded values, 512 levels of nesting, or 2 MiB of string and bytes data. Real databases stay far below these limits. Python’s recursion limit may stop decoding sooner.

Thread Safety

Both the C extension and pure Python implementations are safe for concurrent reads and support Python 3.13+ free-threading. The C extension provides free-threading support on platforms with pthread support (such as Linux and macOS) and Windows. On other platforms, the extension will use GIL-based protection. Calling close() while reads are in progress may cause exceptions in those threads.

Versioning

The MaxMind DB Python module uses Semantic Versioning.

Support

Please report all issues with this code using the GitHub issue tracker

If you are having an issue with a MaxMind service that is not specific to this API, please contact MaxMind support for assistance.

Module

Module for reading MaxMind DB files.

exception maxminddb.InvalidDatabaseError

Bases: RuntimeError

An error thrown when unexpected data is found in the database.

class maxminddb.Mode(*values)

Bases: IntEnum

Database open modes.

These modes control how the MaxMind DB file is opened and read.

AUTO = 0

Try MODE_MMAP_EXT, MODE_MMAP, MODE_FILE in that order. Default mode.

A file object uses MODE_FD.

FD = 16

Database is a binary file object, not a path. This mode implies MODE_MEMORY.

FILE = 4

Read database as standard file. Pure Python.

MEMORY = 8

Load database into memory. Pure Python.

MMAP = 2

Read from memory map. Pure Python.

MMAP_EXT = 1

Use the C extension with memory map.

class maxminddb.Reader(database: DatabaseSource, mode: int = Mode.AUTO)

Bases: object

A pure Python implementation of a reader for the MaxMind DB format.

IP addresses can be looked up using the get method.

close() → None

Close the MaxMind DB file and returns the resources to the system.

Calling this method while reads are in progress may cause exceptions.

closed: bool = True
get(ip_address: str | IPv6Address | IPv4Address) → Record | None

Return the record for the ip_address in the MaxMind DB.

Arguments:

ip_address: an IP address in the standard string notation

get_with_prefix_len(ip_address: str | IPv6Address | IPv4Address) → tuple[Record | None, int]

Return a tuple with the record and the associated prefix length.

Arguments:

ip_address: an IP address in the standard string notation

metadata() → Metadata

Return the metadata associated with the MaxMind DB file.

maxminddb.open_database(database: DatabaseSource, mode: int = Mode.AUTO) → Reader

Open a MaxMind DB database.

Arguments:
database: A path to a valid MaxMind DB file such as a GeoIP database

file, or a binary file object for MODE_FD or MODE_AUTO. MODE_MMAP, MODE_FILE and MODE_MEMORY also accept the file descriptor of a regular file. MODE_MEMORY reads it from its current offset, the others from the start. Without the C extension, MODE_AUTO accepts one too. Once the reader opens a file descriptor, it closes it, even when the file is not a valid database. If an error comes first, for example for a mode that takes no descriptor or for a directory, the caller still owns it. The reader does not close a file object, but it closes a buffer that read() returns if the buffer has close(), such as an mmap.

mode: mode to open the database with. Valid mode are:
  • MODE_MMAP_EXT - use the C extension with memory map.

  • MODE_MMAP - read from memory map. Pure Python.

  • MODE_FILE - read database as standard file. Pure Python.

  • MODE_MEMORY - load database into memory. Pure Python.

  • MODE_FD - the param passed via database is a binary file

    object, not a path. This mode implies MODE_MEMORY.

  • MODE_AUTO - tries MODE_MMAP_EXT, MODE_MMAP, MODE_FILE in that

    order. Reads a file object into memory, as MODE_FD does. Default mode.

Errors

Typed errors thrown by this library.

exception maxminddb.errors.InvalidDatabaseError

Bases: RuntimeError

An error thrown when unexpected data is found in the database.

Database Reader

Pure-Python reader for the MaxMind DB file format.

class maxminddb.reader.Metadata(*, binary_format_major_version: int, binary_format_minor_version: int, build_epoch: int, database_type: str, description: dict[str, str], ip_version: int, languages: list[str], node_count: int, record_size: int)

Bases: object

Metadata for the MaxMind DB reader.

binary_format_major_version: int

The major version number of the binary format used when creating the database.

binary_format_minor_version: int

The minor version number of the binary format used when creating the database.

build_epoch: int

The Unix epoch for the build time of the database.

database_type: str

A string identifying the database type, e.g., “GeoIP2-City”.

description: dict[str, str]

A map from locales to text descriptions of the database.

ip_version: int

The IP version of the data in a database. A value of “4” means the database only supports IPv4. A database with a value of “6” may support both IPv4 and IPv6 lookups.

languages: list[str]

A list of locale codes supported by the database.

property node_byte_size: int

The size of a node in bytes.

node_count: int

The number of nodes in the database.

record_size: int

The bit size of a record in the search tree.

property search_tree_size: int

The size of the search tree.

class maxminddb.reader.Reader(database: DatabaseSource, mode: int = Mode.AUTO)

Bases: object

A pure Python implementation of a reader for the MaxMind DB format.

IP addresses can be looked up using the get method.

close() → None

Close the MaxMind DB file and returns the resources to the system.

Calling this method while reads are in progress may cause exceptions.

closed: bool = True
get(ip_address: str | IPv6Address | IPv4Address) → Record | None

Return the record for the ip_address in the MaxMind DB.

Arguments:

ip_address: an IP address in the standard string notation

get_with_prefix_len(ip_address: str | IPv6Address | IPv4Address) → tuple[Record | None, int]

Return a tuple with the record and the associated prefix length.

Arguments:

ip_address: an IP address in the standard string notation

metadata() → Metadata

Return the metadata associated with the MaxMind DB file.

Types

Types for database records and database arguments.

maxminddb.types.DatabaseSource: TypeAlias = str | bytes | os.PathLike[str] | os.PathLike[bytes] | int | maxminddb.types.SupportsRead

DatabaseSource is a type for the database argument of a reader.

maxminddb.types.RecordDict

RecordDict is a type for dicts in a database record.

alias of dict[str, Record]

maxminddb.types.RecordList

RecordList is a type for lists in a database record.

alias of list[Record]

maxminddb.types.StrOrBytesPath: TypeAlias = str | bytes | os.PathLike[str] | os.PathLike[bytes]

StrOrBytesPath is a type for a path to a database file.

class maxminddb.types.SupportsRead(*args, **kwargs)

SupportsRead is a type for a binary file object for MODE_FD or MODE_AUTO.

read() → bytes

Return the remaining bytes.

maxminddb.types.Primitive

Primitive is a type for a scalar value in a database record.

alias of AnyStr | bool | float | int

maxminddb.types.Record

Record is a type for a value in a database record.

alias of AnyStr | bool | float | int | list[Record] | dict[str, Record]

Indices and tables

copyright:
  1. 2013-2025 by MaxMind, Inc.

license:

Apache License, Version 2.0