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.0.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.0-py3-none-any.whl (6.0 kB view details)

Uploaded Python 3

File details

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

File metadata

  • Download URL: cpf_utils-1.0.0.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.0.tar.gz
Algorithm Hash digest
SHA256 ad556f6c6cc7c8ddf880d185e7c6663e7085d3537509a9a6010163ebf15f2bf0
MD5 47dd2963450a9873058a8e329bc4ac47
BLAKE2b-256 83bdfe359e8debc01069e8e92f21072f7cd3020915f18af3c4688ea10c602ce6

See more details on using hashes here.

File details

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

File metadata

  • Download URL: cpf_utils-1.0.0-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.0-py3-none-any.whl
Algorithm Hash digest
SHA256 2d8c0df5b589cabda87fd11038b5212d7cd98765759ad6f4101a66735fcf0663
MD5 819f0805007ad281c82c22191de681ec
BLAKE2b-256 15e494a07e2ff7bc9813b9704c5703499680cdf54b1cfe45bdd8a6e116f5606d

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