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

Uploaded Python 3

File details

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

File metadata

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

File hashes

Hashes for cpf_gen-1.0.0.tar.gz
Algorithm Hash digest
SHA256 1f57007c7c1aff60a74fd021d6b90087ac9fff9efb1711938cc9f63cb10d1d90
MD5 aa878348ffbda2a7f57ab8de7bdc3dbe
BLAKE2b-256 ffab68f2dd54eab385692db0996db31a6c76b59bf354cf8e44eecb2c70c56492

See more details on using hashes here.

File details

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

File metadata

  • Download URL: cpf_gen-1.0.0-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.0

File hashes

Hashes for cpf_gen-1.0.0-py3-none-any.whl
Algorithm Hash digest
SHA256 5633b9cf89376768a2413ed311406d42b395895e037602d32e7d059210d5ba44
MD5 a56252eab629a4a6e6da8b67fa504274
BLAKE2b-256 3a526f1004db1e3c3560c90dc78d121a836b7ca3c5d83881b8cdce7da4e825e3

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