Skip to main content

Tax Identifiers

Country-aware tax identifier validation, normalization, and metadata resolution for Pydantic models.

Features

  • Validate US tax identifiers against SSN, EIN and ITIN structural rules, with generic normalization for every other country.
  • Resolve SSN allocation metadata: issuing state and issued years.
  • Annotated Pydantic field types that normalize a tax identifier on construction and reject one its country's rules find invalid.
  • Masking and unmasking of tax identifier fields, with the original recoverable.
  • Country resolution from ISO codes, alpha-3 codes and full names.
  • Typed throughout, with a PEP 561 py.typed marker.

Installation

pip install tax-identifiers

Typing

Every field type this package exports is a plain Annotated alias, valid in annotation position:

from pydantic import BaseModel

from tax_identifiers import SSNTaxIdField


class TaxPayer(BaseModel):
    tax_id: SSNTaxIdField

Configuration lives in metadata objects inside Annotated, so a field type is always a name you can annotate with, never a call.

Quick Start

Construct a TaxValidator for a country and validate an identifier. The validator normalizes the value, applies that country's structural rules, and resolves any metadata. Currently, only the US validators have dedicated validation rules; every other country falls back to generic normalization.

from tax_identifiers import TaxValidator, Country, TaxIdentifierType

validator = TaxValidator(Country.US)
result = validator.validate("123-45-6789", TaxIdentifierType.SSN)

result.valid                   # True, passes the SSN reserved-range checks
result.country                 # Country.US
result.tax_id_type             # TaxIdentifierType.SSN
result.metadata.issued_state   # a USState enum, e.g. USState.NEW_YORK ("NY")
result.metadata.issued_years   # e.g. "1936-1950"

TaxValidationResult omits the raw identifier.

Resolving Countries

Country.from_string normalizes codes and names, so "US", "us", "United States", and "USA" all resolve to Country.US. A validator can be built straight from a stored country string:

validator = TaxValidator(Country.from_string(row.country))   # ISO code or full name

A named country without dedicated rules can't decide validity, so it reports valid as None rather than guessing:

TaxValidator(Country.from_string("France")).validate(
    "FR1234567", TaxIdentifierType.FOREIGN_TIN
).valid   # None, no validation rules for France

Country.UNKNOWN is the country-agnostic exception: it accepts any non-empty identifier, so foreign identifiers of any shape validate against it.

An unrecognized country string raises UnknownCountryError:

Country.from_string("Atlantis")   # raises UnknownCountryError

Error Handling

validate raises on malformed or unsupported input. A parseable-but-reserved identifier is not an error. It comes back with valid=False, and a country whose rules cannot decide comes back with valid=None:

from tax_identifiers import InvalidTaxIdError, UnsupportedTaxIdTypeError

validator.validate("666-12-3456", TaxIdentifierType.SSN).valid          # False, 666 is a reserved area
validator.validate("123-45-67890", TaxIdentifierType.SSN)               # raises InvalidTaxIdError, 10 digits
TaxValidator(Country.US).validate("X1", TaxIdentifierType.FOREIGN_TIN)  # raises UnsupportedTaxIdTypeError

Each country handles a fixed set of identifier types, so a field declared with a pair its country does not handle raises UnsupportedTaxIdTypeError when the model class is built, not when a value arrives.

TaxValidationResult.from_tax_identifier returns None for missing or malformed input instead of raising:

from tax_identifiers import TaxValidationResult

summary = TaxValidationResult.from_tax_identifier(
    country=Country.US, tax_id="12-3456789", tax_id_type=TaxIdentifierType.EIN
)
summary.valid   # True

Normalization Utilities

from tax_identifiers import clean_us_tax_identifier, format_us_ssn, format_us_ein, ComparableUsTaxIdentifier

clean_us_tax_identifier(" 123-45-6789 ")                  # "123456789"
format_us_ssn("123456789")                                # "123-45-6789"
format_us_ein("123456789")                                # "12-3456789"
ComparableUsTaxIdentifier("123-45-6789") == "123456789"   # True, equality ignores formatting

Masking Tax Identifiers

A tax ID field carries a country and identifier type and normalizes on construction. TaxIdentifierPairMixin masks the value while keeping the original recoverable; it reads annotation metadata through get_annotated_fields, so it is mixed into a SuperModelPydanticMixin model:

from pydantic_super_model import SuperModelPydanticMixin

from tax_identifiers import SSNTaxIdField, TaxIdentifierPairMixin


class TaxPayer(TaxIdentifierPairMixin, SuperModelPydanticMixin):
    name: str
    tax_id: SSNTaxIdField


record = TaxPayer(name="Jane Doe", tax_id="123-45-6789")
record.tax_id == "123456789"   # normalized on construction

masked = record.to_masked()
masked.tax_id                  # "*******6789"
masked.to_unmask().tax_id      # "123-45-6789", original recovered

A field rejects a value its country's rules find structurally invalid, raising InvalidTaxIdError. Because that subclasses ValueError, pydantic reports it as a ValidationError like any other field failure. A country whose rules cannot decide validity rejects nothing, so today that means SSNTaxIdField rejects reserved SSN ranges and the other aliases accept whatever normalizes.

LenientSSNTaxIdField normalizes and carries the same SSN metadata but does not reject, for parsing payloads from a third party whose values you do not control. Any annotation can opt out the same way with TaxIdFieldOptions(..., assert_validity=False).

The shipped aliases, each naming a country and an identifier type. Every one rejects a value that is already masked.

Alias Country Type
SSNTaxIdField US SSN
LenientSSNTaxIdField US SSN
USTaxIdField US unspecified
ForeignTaxIdField UNKNOWN foreign TIN
UnknownTaxIdField UNKNOWN none

A field that reads a value back from storage already masked, such as "*****6789", adds AllowMasked:

from typing import Annotated

from pydantic import BaseModel

from tax_identifiers import AllowMasked, USTaxIdField


class StoredTaxPayer(BaseModel):
    tax_id: Annotated[USTaxIdField, AllowMasked]

AllowMasked composes with any alias or custom annotation, so masking stays one marker rather than a variant of every name. A masked value is returned untouched, skipping normalization and the validity check.

Leniency is a field option rather than a marker because it is a decision inside the validity check, not a test on the raw input: LenientSSNTaxIdField carries the same SSN country and type metadata but does not reject.

For any other combination, put TaxIdFieldOptions inside an Annotated:

from typing import Annotated

from tax_identifiers import Country, TaxIdentifierType, TaxIdFieldOptions, TaxIdStr

FrenchTinField = Annotated[
    TaxIdStr,
    TaxIdFieldOptions(country=Country.FR, tax_id_type=TaxIdentifierType.FOREIGN_TIN),
]

TaxIdFieldOptions defaults to Country.UNKNOWN with TaxIdentifierType.NONE, a country-agnostic field that normalizes (uppercases) and accepts any non-empty value. Pass country=Country.US to apply a country's rules, along with a tax_id_type that country handles.

Local Development

poetry install --all-extras   # install
poetry run pytest             # run the tests
poetry run black .            # format
poetry run pyright            # type check

Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

tax_identifiers-0.1.0.tar.gz (87.9 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

tax_identifiers-0.1.0-py3-none-any.whl (97.9 kB view details)

Uploaded Python 3

File details

Details for the file tax_identifiers-0.1.0.tar.gz.

File metadata

  • Download URL: tax_identifiers-0.1.0.tar.gz
  • Upload date:
  • Size: 87.9 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/7.0.0 CPython/3.13.14

File hashes

Hashes for tax_identifiers-0.1.0.tar.gz
Algorithm Hash digest
SHA256 2b921197476c0a7ca3329a890a8c606685876dc70543ea53adfd831854906321
MD5 6eca22adacec66c99e4e96493b011080
BLAKE2b-256 60a4bd842157b936b2ee3052d535778f2339cfb8ff65a894faeb0727ed2c7ab2

See more details on using hashes here.

Provenance

The following attestation bundles were made for tax_identifiers-0.1.0.tar.gz:

Publisher: publish-to-pypi.yml on julien777z/tax-identifiers

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

File details

Details for the file tax_identifiers-0.1.0-py3-none-any.whl.

File metadata

  • Download URL: tax_identifiers-0.1.0-py3-none-any.whl
  • Upload date:
  • Size: 97.9 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/7.0.0 CPython/3.13.14

File hashes

Hashes for tax_identifiers-0.1.0-py3-none-any.whl
Algorithm Hash digest
SHA256 4ec44878a9a4473de8d0f3961d19513b1e8b51e6331e9eef952f973c88b2fb9f
MD5 a95806fedd699491873c7b987570b17f
BLAKE2b-256 37bc8a1183792b770ad3a7925c68deac36ae7fc5f1567ef67d40f0133601c360

See more details on using hashes here.

Provenance

The following attestation bundles were made for tax_identifiers-0.1.0-py3-none-any.whl:

Publisher: publish-to-pypi.yml on julien777z/tax-identifiers

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

Release history Release notifications | RSS feed

This release

0.1.0 This release

2 files

0.0.4

2 files

0.0.3

2 files

0.0.2

2 files

0.0.1

2 files

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