docs
This library turns Spanish identification numbers into first-class Python types. Each class (NIF, DNI, NIE) subclasses str, validates its control letter on construction, and plugs straight into Pydantic so you can drop it into your data models without writing bespoke validators.
⚠️ AI-generated library: This library may contain severe vulnerabilities and should not be trusted for critical workflows. Use at your own risk; it was produced with the Codex AI assistant.
Installation¶
pip¶
python -m pip install spanish-nif
uv¶
uv pip install spanish-nif
Quick examples¶
from spanish_nif import DNI, NIE, NIF
DNI("12345678Z") # returns a validated DNI string
NIE.is_valid("X1234567L") # -> True
NIF("K0867756N").variant # -> "klm"
from spanish_nif import DNI, NIF
fresh_dni = DNI.random()
some_nif = NIF.random() # variant chosen automatically
klm_nif = NIF.random(variant="klm")
from pydantic import BaseModel
from spanish_nif import NIF
class TaxPayer(BaseModel):
nif: NIF
tax_payer = TaxPayer(nif="12345678Z")
assert tax_payer.nif == "12345678Z"
- Invalid inputs raise an
InvalidIdentificationsubclass with a helpful message. - Normalisation uppercases the value and validates the control-letter sequence; inputs must already be correctly formatted.
- Need dummy data for tests or demos? Each class exposes a
.random()helper; pass arandom.Randominstance only if you require deterministic output.
Related Projects¶
- validarnif – Python module exposing procedural validators for NIF/NIE/CIF and optional preprocessing utilities; spanish-nif instead wraps those rules in reusable string subclasses with Pydantic/JSON Schema integration.
- spanish-dni – Python package with validator functions and generators focused on list processing; our library prioritises strong typing and schema metadata for application models.
- spain-id – TypeScript/Node toolkit validating NIF/NIE/CIF in browser and server environments, whereas spanish-nif targets Python workflows.
- ulabox/nif-validator – PHP utility offering static
isValid*helpers for CIF, DNI and NIE; our package emphasises typed models and Pydantic interoperability rather than imperative checks. - criptalia/spanish_dni_validator – Go port of the ulabox/NIF validator covering DNI, NIE and CIF with
IsValid*helpers; spanish-nif instead provides Python string subclasses with declarative Pydantic integration.