Skip to main content

peru-ubigeo

Python License Pydantic v2

Librería Python agnóstica de framework para consulta y validación de códigos ubigeo peruanos. Diseñada para integración con librerías de documentos electrónicos SUNAT (einvoice, GRE, SIRE, CPE).


Características

  • Sistema de código dual — códigos INEI + RENIEC con mapeo por distrito
  • Modelos Pydantic v2 — Country, Department, Province, District, tipo validado UbigeoCode
  • Sin dependencia de framework — Python puro; compatible con FastAPI, Django, Tryton o scripts independientes
  • Arquitectura Hexagonal — cambia la fuente de datos sin tocar la lógica de negocio
  • Datos embebidos estáticos — sin llamadas a red; los datos se actualizan con cada nueva versión del paquete
  • Tipado completo — PEP 561 (py.typed), compatible con mypy modo estricto
  • Python 3.11+ — tipado moderno en todo el código

Instalación

pip install peru-ubigeo

Inicio rápido

from peru_ubigeo import UbigeoRegistry

registry = UbigeoRegistry()

# ── Búsqueda ──────────────────────────────────────────────────────────
district = registry.get_by_code("150101")        # INEI (por defecto)
print(district.name)                             # LIMA
print(district.department_code)                  # 15
print(district.province_code)                    # 1501

district = registry.get_by_reniec_code("150101") # búsqueda RENIEC

# ── Consultas jerárquicas ─────────────────────────────────────────────
departments = registry.get_departments()          # list[Department] — 25 en total
provinces   = registry.get_provinces("15")        # list[Province]
districts   = registry.get_districts("15", "01") # list[District]

# ── Validación ───────────────────────────────────────────────────────
registry.is_valid_code("150101")   # True
registry.is_valid_code("XXXXXX")   # False

# ── Normalización ────────────────────────────────────────────────────
registry.normalize(" 150101 ")     # "150101"  (elimina espacios)
registry.normalize("10101")        # "010101"  (rellena con ceros a la izquierda)

Arquitectura

peru_ubigeo/
├── __init__.py                # API pública
├── py.typed                   # Marcador PEP 561
├── domain/
│   ├── __init__.py
│   ├── models.py              # Modelos Pydantic v2 + tipo UbigeoCode
│   ├── exceptions.py          # Jerarquía UbigeoError
│   └── ports.py               # UbigeoRepositoryPort (ABC)
├── application/
│   ├── __init__.py
│   └── registry.py            # UbigeoRegistry (casos de uso)
├── infrastructure/
│   ├── __init__.py
│   └── json_repository.py     # Adaptador JsonUbigeoRepository
└── data/
    ├── inei/                  # ubigeo_inei.json
    └── reniec/                # ubigeo_reniec.json

Dirección de dependencias: infrastructure → application → domain


Repositorio personalizado

Inyecta cualquier fuente de datos que implemente UbigeoRepositoryPort:

from peru_ubigeo import UbigeoRegistry
from peru_ubigeo.domain.ports import UbigeoRepositoryPort

class MyDatabaseRepository(UbigeoRepositoryPort):
    ...

registry = UbigeoRegistry(repository=MyDatabaseRepository())

Manejo de errores

from peru_ubigeo import (
    UbigeoRegistry,
    InvalidUbigeoCodeError,
    UbigeoNotFoundError,
    DataSourceError,
)

registry = UbigeoRegistry()

try:
    district = registry.get_by_code("XYZ")
except InvalidUbigeoCodeError as e:
    print(e)  # mensaje en español
except UbigeoNotFoundError as e:
    print(e)  # mensaje en español
except DataSourceError as e:
    print(e)  # mensaje en español
Excepción Cuándo se lanza
InvalidUbigeoCodeError El código no tiene 6 dígitos numéricos
UbigeoNotFoundError Formato válido pero sin coincidencia en los datos
DataSourceError Archivo JSON faltante o corrupto

Todas heredan de UbigeoError.


Fuentes de datos

Fuente Estándar Uso
INEI Códigos geográficos nacionales oficiales Por defecto
RENIEC Códigos del registro civil (pueden diferir del INEI) Documentos electrónicos SUNAT

Los datos están embebidos estáticamente en el paquete; las actualizaciones se distribuyen como nuevas versiones.


Desarrollo

git clone https://github.com/csotelo/peru-ubigeo
cd peru-ubigeo
pip install -e ".[dev]"

# Ejecutar tests
pytest

# Tests con reporte de cobertura
pytest --cov=peru_ubigeo --cov-report=term-missing

Integración con librerías SUNAT

UbigeoCode es un tipo validado que puedes importar directamente en peru-einvoice, peru-gre, peru-sire y peru-cpe:

from peru_ubigeo import UbigeoRegistry, UbigeoCode

def build_address(ubigeo_str: str) -> dict:
    registry = UbigeoRegistry()
    code: UbigeoCode = registry.normalize(ubigeo_str)
    district = registry.get_by_code(code)
    return {
        "ubigeo": code,
        "district": district.name,
        "province": district.province_code,
        "department": district.department_code,
    }

Licencia

Distribuido bajo la licencia Apache 2.0. Ver LICENSE para más detalles.

Copyright 2024 Contributors

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

Descargo de responsabilidad

Este proyecto no es un producto oficial de SUNAT, INEI ni RENIEC.

peru-ubigeo es una librería open source desarrollada de forma independiente por la comunidad. Los datos de ubigeo incluidos provienen de fuentes públicas oficiales (INEI y RENIEC), pero este paquete no está respaldado, afiliado ni avalado por ninguna entidad del Estado peruano.

El uso de esta librería es bajo la responsabilidad del desarrollador. Se recomienda verificar los datos con las fuentes oficiales ante cualquier uso en producción que tenga implicancias legales o tributarias.

Metadata

Release files for peru-ubigeo 1.0.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for peru-ubigeo 1.0.0
File Size Uploaded Provenance Actions
peru_ubigeo-1.0.0.tar.gz 26.6 kB With provenance Details for peru_ubigeo-1.0.0.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for peru-ubigeo 1.0.0
File Interpreter ABI Platform Actions
peru_ubigeo-1.0.0-py3-none-any.whl Python 3 none any Details for peru_ubigeo-1.0.0-py3-none-any.whl

Total release size: 53.8 kB

Release files / peru_ubigeo-1.0.0.tar.gz

Download URL peru_ubigeo-1.0.0.tar.gz
Size 26.6 kB
Tags Source
SHA-256 checksum
How to use checksums
aa8e5bb72acdb1a9b75ba851472a3fd4fa27d329141d5f2ee18c03f470c45b1b
BLAKE2b-256 checksum
How to use checksums
99d2d81235b026bae5a5ce55613d5f903d017c32baa8597ed5bbce6e4e3e2ad3
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/6.1.0 CPython/3.13.12

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Jun 1, 2026.

Transparency log

Release files / peru_ubigeo-1.0.0-py3-none-any.whl

Download URL peru_ubigeo-1.0.0-py3-none-any.whl
Size 27.2 kB
Tags Python 3
SHA-256 checksum
How to use checksums
e783580f8aa8f0ad392a4c890fd5820728fb16b0860edf6ed67e3b66e1fccc1c
BLAKE2b-256 checksum
How to use checksums
e82a9215a857e917753199eea2f617f5cf3e73faf773f6d2ba262f8afdd34e01
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/6.1.0 CPython/3.13.12

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Jun 1, 2026.

Transparency log

Security for peru-ubigeo 1.0.0

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

Full provenance

Both files in this release have been uploaded with provenance metadata.

Select from 2 files

Attestation for peru_ubigeo-1.0.0.tar.gz

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Jun 1, 2026.

Transparency log

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Release history Release notifications | RSS feed

This release

1.0.0 This release

2 release files Full provenance

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page