Consulta y validación de códigos ubigeo peruanos (INEI + RENIEC) para integraciones SUNAT.
Project description
peru-ubigeo
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 validadoUbigeoCode - 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-ubigeoes 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.
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
File details
Details for the file peru_ubigeo-1.0.0.tar.gz.
File metadata
- Download URL: peru_ubigeo-1.0.0.tar.gz
- Upload date:
- Size: 26.6 kB
- Tags: Source
- Uploaded using Trusted Publishing? Yes
- Uploaded via: twine/6.1.0 CPython/3.13.12
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
aa8e5bb72acdb1a9b75ba851472a3fd4fa27d329141d5f2ee18c03f470c45b1b
|
|
| MD5 |
33b727125fdcddbae39045866db3f901
|
|
| BLAKE2b-256 |
99d2d81235b026bae5a5ce55613d5f903d017c32baa8597ed5bbce6e4e3e2ad3
|
Provenance
The following attestation bundles were made for peru_ubigeo-1.0.0.tar.gz:
Publisher:
publish.yml on csotelo/peru-ubigeo
-
Statement:
-
Statement type:
https://in-toto.io/Statement/v1 -
Predicate type:
https://docs.pypi.org/attestations/publish/v1 -
Subject name:
peru_ubigeo-1.0.0.tar.gz -
Subject digest:
aa8e5bb72acdb1a9b75ba851472a3fd4fa27d329141d5f2ee18c03f470c45b1b - Sigstore transparency entry: 1689792698
- Sigstore integration time:
-
Permalink:
csotelo/peru-ubigeo@e29045ccd77c6453acc2f2137539e623e635f702 -
Branch / Tag:
refs/tags/v1.0.0 - Owner: https://github.com/csotelo
-
Access:
public
-
Token Issuer:
https://token.actions.githubusercontent.com -
Runner Environment:
github-hosted -
Publication workflow:
publish.yml@e29045ccd77c6453acc2f2137539e623e635f702 -
Trigger Event:
release
-
Statement type:
File details
Details for the file peru_ubigeo-1.0.0-py3-none-any.whl.
File metadata
- Download URL: peru_ubigeo-1.0.0-py3-none-any.whl
- Upload date:
- Size: 27.2 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? Yes
- Uploaded via: twine/6.1.0 CPython/3.13.12
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
e783580f8aa8f0ad392a4c890fd5820728fb16b0860edf6ed67e3b66e1fccc1c
|
|
| MD5 |
c44457865a853f09019782186b690b3f
|
|
| BLAKE2b-256 |
e82a9215a857e917753199eea2f617f5cf3e73faf773f6d2ba262f8afdd34e01
|
Provenance
The following attestation bundles were made for peru_ubigeo-1.0.0-py3-none-any.whl:
Publisher:
publish.yml on csotelo/peru-ubigeo
-
Statement:
-
Statement type:
https://in-toto.io/Statement/v1 -
Predicate type:
https://docs.pypi.org/attestations/publish/v1 -
Subject name:
peru_ubigeo-1.0.0-py3-none-any.whl -
Subject digest:
e783580f8aa8f0ad392a4c890fd5820728fb16b0860edf6ed67e3b66e1fccc1c - Sigstore transparency entry: 1689792830
- Sigstore integration time:
-
Permalink:
csotelo/peru-ubigeo@e29045ccd77c6453acc2f2137539e623e635f702 -
Branch / Tag:
refs/tags/v1.0.0 - Owner: https://github.com/csotelo
-
Access:
public
-
Token Issuer:
https://token.actions.githubusercontent.com -
Runner Environment:
github-hosted -
Publication workflow:
publish.yml@e29045ccd77c6453acc2f2137539e623e635f702 -
Trigger Event:
release
-
Statement type: