Skip to main content

Utility functions to deal with CPF data (Brazilian personal ID)

Project description

cpf-utils for Python

PyPI Version PyPI Downloads Python Version Test Status Last Update Date Project License

Toolkit to deal with CPF data (Brazilian personal ID): validation, formatting and generation of valid IDs.

Python Support

Python 3.10 Python 3.11 Python 3.12 Python 3.13 Python 3.14
Passing ✔ Passing ✔ Passing ✔ Passing ✔ Passing ✔

Installation

$ pip install cpf-utils

Import

# Using class-based resource
from cpf_utils import CpfUtils

# Or using function-based approach
from cpf_utils import cpf_fmt, cpf_gen, cpf_val

# Or using the default instance
from cpf_utils import cpf_utils

Usage

Object-Oriented Usage

The CpfUtils class provides a unified interface for all CPF operations:

cpf_utils = CpfUtils()
cpf = '93247057062'

# Format CPF
print(cpf_utils.format(cpf))       # returns '932.470.570-62'

# Validate CPF
print(cpf_utils.is_valid(cpf))      # returns True

# Generate CPF
print(cpf_utils.generate())          # returns '65453043078'

With Configuration Options

You can configure the formatter and generator options in the constructor:

from cpf_fmt import CpfFormatterOptions
from cpf_gen import CpfGeneratorOptions

cpf_utils = CpfUtils(
    formatter=CpfFormatterOptions(
        hidden=True,
        hidden_key='#',
        hidden_start=3,
        hidden_end=10
    ),
    generator=CpfGeneratorOptions(format=True)
)

cpf = '93247057062'
print(cpf_utils.format(cpf))       # returns '932.###.###-##'
print(cpf_utils.generate())          # returns '730.085.350-06'

The options can be provided to the constructor or the respective methods. If passed to the constructor, the options will be attached to the CpfUtils instance. When passed to the methods, it only applies the options to that specific call.

cpf_utils = CpfUtils(
    formatter=CpfFormatterOptions(hidden=True)
)

cpf = '93247057062'
print(cpf_utils.format(cpf))                  # '932.***.***.***-**'
print(cpf_utils.format(cpf, hidden=False))    # '932.470.570-62' (overrides instance options)
print(cpf_utils.format(cpf))                  # '932.***.***.***-**' (uses instance options again)

Functional Programming

The package also provides standalone functions for each operation:

cpf = '93247057062'

# Format CPF
print(cpf_fmt(cpf))                 # returns '932.470.570-62'

# Validate CPF
print(cpf_val(cpf))                 # returns True

# Generate CPF
print(cpf_gen())                     # returns '65453043078'

Or use the default instance:

from cpf_utils import cpf_utils

cpf = '93247057062'
print(cpf_utils.format(cpf))        # returns '932.470.570-62'
print(cpf_utils.is_valid(cpf))      # returns True
print(cpf_utils.generate())          # returns '65453043078'

API Reference

Formatting (cpf_fmt / CpfUtils.format)

Formats a CPF string with customizable delimiters and masking options.

cpf_utils.format(
    cpf_string: str,
    hidden: bool | None = None,
    hidden_key: str | None = None,
    hidden_start: int | None = None,
    hidden_end: int | None = None,
    dot_key: str | None = None,
    dash_key: str | None = None,
    escape: bool | None = None,
    on_fail: Callable | None = None,
) -> str

Parameters:

Parameter Type Default Description
hidden bool | None False Whether to hide digits with a mask
hidden_key str | None '*' Character to replace hidden digits
hidden_start int | None 3 Starting index for hidden range (0-10)
hidden_end int | None 10 Ending index for hidden range (0-10)
dot_key str | None '.' String to replace dot characters
dash_key str | None '-' String to replace dash character
escape bool | None False Whether to HTML escape the result
on_fail Callable | None lambda value, error=None: value Fallback function for invalid input

Examples:

cpf = '93247057062'

# Basic formatting
print(cpf_fmt(cpf))                 # '932.470.570-62'

# With hidden digits
print(cpf_fmt(cpf, hidden=True))    # '932.***.***.***-**'

# Custom delimiters
print(cpf_fmt(cpf, dot_key='', dash_key='_'))  # '932470570_62'

# Custom hidden range
print(cpf_fmt(cpf, hidden=True, hidden_start=0, hidden_end=5, hidden_key='#'))  # '###.##0.570-62'

Generation (cpf_gen / CpfUtils.generate)

Generates valid CPF numbers with optional formatting and prefix completion.

cpf_utils.generate(
    format: bool | None = None,
    prefix: str | None = None,
) -> str

Parameters:

Parameter Type Default Description
format bool | None False Whether to format the output
prefix str | None '' Prefix to complete with valid digits (1-9 digits)

Examples:

# Generate random CPF
print(cpf_gen())                     # '65453043078'

# Generate formatted CPF
print(cpf_gen(format=True))          # '730.085.350-06'

# Complete a prefix
print(cpf_gen(prefix='456237'))      # '45623741038'

# Complete and format
print(cpf_gen(prefix='456237410', format=True))  # '456.237.410-38'

Validation (cpf_val / CpfUtils.is_valid)

Validates CPF numbers using the official algorithm.

cpf_utils.is_valid(cpf_string: str) -> bool

Examples:

# Valid CPF
print(cpf_val('93247057062'))        # True
print(cpf_val('932.470.570-62'))     # True

# Invalid CPF
print(cpf_val('93247057063'))        # False

Advanced Usage

Accessing Individual Components

You can access the individual formatter, generator, and validator instances:

cpf_utils = CpfUtils()

# Access individual components
formatter = cpf_utils.formatter
generator = cpf_utils.generator
validator = cpf_utils.validator

# Use them directly
formatter.format('93247057062', hidden=True)
generator.generate(format=True)
validator.is_valid('93247057062')

Custom Error Handling

cpf = '123'  # Invalid length

# Custom fallback
def custom_fail(value, error=None):
    return f"Invalid CPF: {value}"

print(cpf_fmt(cpf, on_fail=custom_fail))  # 'Invalid CPF: 123'

# Return original value (default behavior)
print(cpf_fmt(cpf))  # '123'

Dependencies

This package is built on top of the following specialized packages:

Contribution & Support

We welcome contributions! Please see our Contributing Guidelines for details. But if you find this project helpful, please consider:

License

This project is licensed under the MIT License - see the LICENSE file for details.

Changelog

See CHANGELOG for a list of changes and version history.


Made with ❤️ by Lacus Solutions

Project details


Download files

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

Source Distribution

cpf_utils-1.0.1.tar.gz (6.3 kB view details)

Uploaded Source

Built Distribution

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

cpf_utils-1.0.1-py3-none-any.whl (6.0 kB view details)

Uploaded Python 3

File details

Details for the file cpf_utils-1.0.1.tar.gz.

File metadata

  • Download URL: cpf_utils-1.0.1.tar.gz
  • Upload date:
  • Size: 6.3 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.14.2

File hashes

Hashes for cpf_utils-1.0.1.tar.gz
Algorithm Hash digest
SHA256 8efa78e8dfcde44c587dd0422f87f7355fee1ee20b0e55695257ad319f0791a4
MD5 2003786688aef3fa40d0ff763ea48361
BLAKE2b-256 5c739c0204e66ccac663a7d6eb83aa2e92b11b6aabfedef4d899052f261d5225

See more details on using hashes here.

File details

Details for the file cpf_utils-1.0.1-py3-none-any.whl.

File metadata

  • Download URL: cpf_utils-1.0.1-py3-none-any.whl
  • Upload date:
  • Size: 6.0 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.14.2

File hashes

Hashes for cpf_utils-1.0.1-py3-none-any.whl
Algorithm Hash digest
SHA256 bc56384b4875c8a217546487982f56a0eecdf7509d94236e1eb5c1f796ae8882
MD5 da3261729c7f1f30a4da3f1478f46bc0
BLAKE2b-256 6abd16fd3c4b7baa6e92283b5a73ebdbb0f71f574c70e2ad62bfeef85698e550

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page