types-geoip2

3.0.0 · active · verified Mon Apr 13

types-geoip2 provides PEP 561 compliant typing stubs for the geoip2 library. It enables static type checkers like mypy, PyCharm, and pytype to provide robust type checking and autocompletion for code using the geoip2 package. These stubs are maintained as part of the python/typeshed project on GitHub, with new versions automatically released to PyPI frequently (up to once a day) to reflect updates and improvements in typeshed.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to use `geoip2.database.Reader` with the `types-geoip2` stub package. When `types-geoip2` is installed alongside `geoip2`, type checkers can infer the types of objects returned by `geoip2` functions and methods, providing benefits like autocompletion and early error detection. You will need to download a GeoLite2-City.mmdb database file from MaxMind for the database lookup functionality.

import geoip2.database
import os

# Ensure you have a GeoLite2-City.mmdb file available for database lookups.
# Download from: https://dev.maxmind.com/geoip/downloads/maxmind-databases/
# For this example, we assume it's in the current directory or specified path.
# Replace with a real path if needed.
DB_PATH = os.environ.get('GEOLITE2_CITY_DB_PATH', 'GeoLite2-City.mmdb')

# If geoip2.database.Reader is initialized without the stub, type checkers might not know its methods.
# With types-geoip2 installed, mypy (or other type checkers) will correctly infer types.
reader: geoip2.database.Reader
try:
    reader = geoip2.database.Reader(DB_PATH)
except geoip2.errors.AddressNotFoundError:
    print(f"Database file not found at {DB_PATH}. Please provide a valid path or download the database.")
    exit(1)
except Exception as e:
    print(f"An error occurred initializing the database reader: {e}")
    exit(1)


# Example IP address
ip_address = '8.8.8.8' # Google Public DNS

try:
    response = reader.city(ip_address)
    print(f"IP: {ip_address}")
    print(f"Country Name: {response.country.name}")
    print(f"City Name: {response.city.name}")
    print(f"Latitude: {response.location.latitude}")
    print(f"Longitude: {response.location.longitude}")

    # Type checker will correctly identify `response` as geoip2.models.City
    # and `response.country` as geoip2.records.Country
    reveal_type(response) # For mypy to show the inferred type

except geoip2.errors.AddressNotFoundError:
    print(f"IP address {ip_address} not found in the database.")
except Exception as e:
    print(f"An error occurred during lookup: {e}")
finally:
    reader.close()

# To run type checking, save this as `example.py` and run `mypy example.py`

view raw JSON →