Skip to main content

Utility function to generate valid CPF (Brazilian personal ID)

Project description

cpf-gen for Python

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

Utility function/class to generate valid CPF (Brazilian personal ID).

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-gen

Import

# Using class-based resource
from cpf_gen import CpfGenerator

# Or using function-based one
from cpf_gen import cpf_gen

Usage

Object-Oriented Usage

generator = CpfGenerator()
cpf = generator.generate()  # returns '47844241055'

# With options
cpf = generator.generate(
    format=True
)  # returns '478.442.410-55'

cpf = generator.generate(
    prefix='528250911'
)  # returns '52825091138'

cpf = generator.generate(
    prefix='528250911',
    format=True
)  # returns '528.250.911-38'

The options can be provided to the constructor or the generate() method. If passed to the constructor, the options will be attached to the CpfGenerator instance. When passed to the generate() method, it only applies the options to that specific call.

generator = CpfGenerator(format=True)

cpf1 = generator.generate()  # '478.442.410-55' (uses instance options)
cpf2 = generator.generate(format=False)  # '47844241055' (overrides instance options)
cpf3 = generator.generate()  # '123.456.789-01' (uses instance options again)

Functional programming

The helper function cpf_gen() is just a functional abstraction. Internally it creates an instance of CpfGenerator and calls the generate() method right away.

cpf = cpf_gen()  # returns '47844241055'

cpf = cpf_gen(format=True)  # returns '478.442.410-55'

cpf = cpf_gen(prefix='528250911')  # returns '52825091138'

cpf = cpf_gen(prefix='528250911', format=True)  # returns '528.250.911-38'

Generator Options

Parameter Type Default Description
format bool | None False Whether to format the output with dots and dash
prefix str | None '' If you have CPF initials and want to complete it with valid digits. The string provided must contain between 0 and 9 digits!

Error Handling

The package raises specific exceptions for different error scenarios:

CpfGeneratorPrefixLengthError

Raised when the prefix length exceeds the maximum allowed (9 digits).

from cpf_gen import CpfGenerator, CpfGeneratorPrefixLengthError

try:
    generator = CpfGenerator(prefix="1234567890") # 10 digits (too many)
except CpfGeneratorPrefixLengthError as e:
    print(e)  # The prefix length must be less than or equal to 9. Got 10.

CpfGeneratorPrefixNotValidError

Raised when the input is forbidden for some restriction, like repeated digits like 111.111.111, 222.222.222, 333.333.333 and so on.

from cpf_gen import CpfGenerator, CpfGeneratorPrefixNotValidError

try:
    generator = CpfGenerator(prefix="777777777")
except CpfGeneratorPrefixNotValidError as e:
    print(e)  # The prefix "777777777" is invalid. Repeated digits are not considered valid.

Catch any error from the package

All errors extend from a common error instance CpfGeneratorError, so you can use this type to handle any error thrown by the module.

from cpf_gen import CpfGeneratorError

try:
  # some risky code run
except CpfGeneratorError as e:
  # do something

Features

  • Multiple Usage Patterns: Supports both object-oriented and functional programming styles
  • Flexible Options: Configure formatting and prefix at instance or method level
  • Valid CPF Generation: Always generates CPFs with correct check digits
  • Type Safety: Built with Python 3.10+ type hints
  • Zero Dependencies: Only depends on cpf-dv for check digit calculation
  • Comprehensive Error Handling: Specific exceptions for different error scenarios

API Reference

CpfGenerator Class

Constructor

CpfGenerator(format: bool | None = None, prefix: str | None = None) -> CpfGenerator

Creates a new CpfGenerator instance with optional default options.

Parameters:

  • format (bool | None): Whether to format the output with dots and dash. Defaults to False.
  • prefix (str | None): CPF prefix (0-9 digits). Defaults to empty string.

Returns:

  • CpfGenerator: A new instance ready to generate CPFs

Methods

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

Generates a valid CPF according to the given options.

Parameters:

  • format (bool | None): Whether to format the output. If None, uses instance option.
  • prefix (str | None): CPF prefix (0-9 digits). If None, uses instance option.

Returns:

  • str: A valid CPF string (formatted or unformatted)

Properties

options: CpfGeneratorOptions

Direct access to the options manager for the CPF generator.

generator = CpfGenerator()
generator.options.format = True
generator.options.prefix = "123456789"

cpf_gen Function

cpf_gen(format: bool | None = None, prefix: str | None = None) -> str

Functional wrapper that creates a CpfGenerator instance and calls generate() immediately.

Parameters:

  • format (bool | None): Whether to format the output. Defaults to False.
  • prefix (str | None): CPF prefix (0-9 digits). Defaults to empty string.

Returns:

  • str: A valid CPF string (formatted or unformatted)

Examples

from cpf_gen import CpfGenerator, cpf_gen

# Basic usage
cpf1 = cpf_gen()  # '47844241055'
cpf2 = cpf_gen(format=True)  # '478.442.410-55'

# With prefix
cpf3 = cpf_gen(prefix='123456789')  # '12345678901'
cpf4 = cpf_gen(prefix='123456789', format=True)  # '123.456.789-01'

# Using class-based approach
generator = CpfGenerator(format=True)
cpf5 = generator.generate()  # '478.442.410-55'
cpf6 = generator.generate(format=False)  # '47844241055' (overrides instance option)

# Modify options directly
generator.options.prefix = "987654321"
cpf7 = generator.generate()  # '987.654.321-XX' (formatted with prefix)

Dependencies

  • Python: >= 3.10
  • cpf-dv: for check digit calculation

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_gen-1.0.1.tar.gz (9.1 kB view details)

Uploaded Source

Built Distribution

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

cpf_gen-1.0.1-py3-none-any.whl (7.6 kB view details)

Uploaded Python 3

File details

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

File metadata

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

File hashes

Hashes for cpf_gen-1.0.1.tar.gz
Algorithm Hash digest
SHA256 c35fee79707fd0906eb29d23437e4806aa4d3e8292c3f59862d0c8a397826a9e
MD5 73d88ca583ba0b14499e42a759837e56
BLAKE2b-256 a2181602162b502c4932a906b697a28a338052d86615a9ea0dd81a272aef46c0

See more details on using hashes here.

File details

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

File metadata

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

File hashes

Hashes for cpf_gen-1.0.1-py3-none-any.whl
Algorithm Hash digest
SHA256 f8d9fb956ce40c992b61af535f8afc8308914c2a02793f194505625c753628c0
MD5 ae11c9e8b39f28a9683cf3cc72cf8f44
BLAKE2b-256 af6560db11f042b38a233796c93cced58131b7ae27eb64d3cbf387ed38791368

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