Skip to content

national_ids

national_ids

Checks for whether a value is a locale's personal national ID, using python-stdnum.

Functions:

Name Description
national_id_check

Return whether a value is a personal national ID of locale's country, or None without a check.

national_id_check(locale, *, loose=False) cached

Return whether a value is a personal national ID of locale's country, or None without a check.

The country is the locale's region, so en_CA and fr_CA both check Canadian SINs. Whitespace is ignored, since python-stdnum's checks only strip some separators.

Parameters:

Name Type Description Default
locale str

Locale whose country's IDs to check, such as en_US.

required
loose bool

Also use checks that many other numbers pass, such as the Dutch BSN. Fine for choosing how to replace a value already typed as a national ID, too loose for detecting one.

False
Example

national_id_check("en_US") accepts "123-45-6789", "123456789", and "123 45 6789", but not "912-45-6789", an ITIN. national_id_check("en_GB") is None.

Source code in src/nemo_safe_synthesizer/pii_replacer/replacement/national_ids.py
@lru_cache
def national_id_check(locale: str, *, loose: bool = False) -> Callable[[str], bool] | None:
    """Return whether a value is a personal national ID of ``locale``'s country, or ``None`` without a check.

    The country is the locale's region, so ``en_CA`` and ``fr_CA`` both check Canadian SINs. Whitespace is
    ignored, since python-stdnum's checks only strip some separators.

    Args:
        locale: Locale whose country's IDs to check, such as ``en_US``.
        loose: Also use checks that many other numbers pass, such as the Dutch BSN. Fine for choosing how to
            replace a value already typed as a national ID, too loose for detecting one.

    Example:
        ``national_id_check("en_US")`` accepts ``"123-45-6789"``, ``"123456789"``, and ``"123 45 6789"``, but not
        ``"912-45-6789"``, an ITIN. ``national_id_check("en_GB")`` is ``None``.
    """
    _, _, region = locale.replace("-", "_").rpartition("_")
    modules = _PERSONAL_ID_MODULES.get(region.upper()) or (
        _LOOSE_PERSONAL_ID_MODULES.get(region.upper()) if loose else None
    )
    if modules is None:
        return None
    validators = tuple(importlib.import_module(f"stdnum.{module}").is_valid for module in modules)

    def is_national_id(value: str) -> bool:
        compact = "".join(value.split())
        return any(_passes(is_valid, compact) for is_valid in validators)

    return is_national_id