Utilities to deal with CNPJ (Brazilian Business Tax ID)
Project description
🚀 Full support for the new alphanumeric CNPJ format.
Utilities to deal with CNPJ (Brazilian Business Tax ID). This package wraps cnpj-fmt, cnpj-gen, and cnpj-val in a single API and re-exports their public resources.
Python Support
| Passing ✔ | Passing ✔ | Passing ✔ | Passing ✔ | Passing ✔ |
Features
- ✅ Unified API: One default instance with
format,generate, andis_valid; or use the underlyingcnpj_fmt,cnpj_gen, andcnpj_valhelpers - ✅ Alphanumeric CNPJ: Format, generate, and validate 14-character numeric or alphanumeric CNPJ
- ✅ Reusable instance:
CnpjUtilsclass with optional default settings (formatter, generator, validator options or instances) - ✅ Full re-exports: All formatter, generator, and validator classes, options, and exceptions from the three component packages
- ✅ Type hints: Built for Python 3.10+ with full type annotations
- ✅ Flexible input:
format()andis_valid()acceptstror a sequence ofstr(elements concatenated in order) - ✅ Per-call overrides: Instance defaults plus keyword or mapping overrides on each method call
- ✅ Error handling: Same type errors and exceptions as the underlying packages
Installation
$ pip install cnpj-utils
This installs cnpj-utils together with cnpj-fmt, cnpj-gen, and cnpj-val. You do not need separate pip install calls for the component packages when using cnpj-utils.
Quick Start
from cnpj_utils import CnpjUtils, cnpj_fmt, cnpj_gen, cnpj_val, cnpj_utils
Basic usage with the default singleton:
from cnpj_utils import cnpj_utils
cnpj = '03603568000195'
cnpj_utils.format(cnpj) # '03.603.568/0001-95'
cnpj_utils.format(cnpj, hidden=True) # '03.603.***/****-**'
cnpj_utils.format( # '03603568|0001_95'
cnpj,
dot_key='',
slash_key='|',
dash_key='_',
)
cnpj_utils.generate() # e.g. 'AB123CDE000155' (14-char alphanumeric)
cnpj_utils.generate(format=True) # e.g. 'AB.123.CDE/0001-55'
cnpj_utils.generate(prefix='45623767') # e.g. '45623767000296'
cnpj_utils.generate(type='numeric') # e.g. '65453043000178' (digits only)
cnpj_utils.is_valid('98765432000198') # True
cnpj_utils.is_valid('98.765.432/0001-98') # True
cnpj_utils.is_valid('1QB5UKALPYFP59') # True (alphanumeric)
cnpj_utils.is_valid('98765432000199') # False
Usage
You can work in three equivalent ways:
cnpj_utils— pre-built singleton for quick one-off calls.CnpjUtils— configurable instance with shared defaults across format, generate, and validate.- Component classes and helpers —
CnpjFormatter,CnpjGenerator,CnpjValidator, andcnpj_fmt(),cnpj_gen(),cnpj_val()(same classes used internally byCnpjUtils).
All three approaches expose the same options and behavior. For exhaustive option tables and component-specific details, see the README of each bundled package.
Formatter options
When calling format(cnpj_input, options=None, …), all options are optional:
| Option | Type | Default | Description |
|---|---|---|---|
hidden |
bool |
False |
When True, mask characters in hidden_start–hidden_end with hidden_key |
hidden_key |
str |
'*' |
Character(s) used to replace masked characters |
hidden_start |
int |
5 |
Start index (0–13, inclusive) of the range to hide |
hidden_end |
int |
13 |
End index (0–13, inclusive) of the range to hide |
dot_key |
str |
'.' |
Dot delimiter (e.g. in 12.345.678) |
slash_key |
str |
'/' |
Slash delimiter (e.g. before branch …/0001-90) |
dash_key |
str |
'-' |
Dash delimiter (e.g. before check digits …-90) |
escape |
bool |
False |
When True, escape HTML special characters in the result |
encode |
bool |
False |
When True, URL-encode the result (similar to JavaScript encodeURIComponent) |
on_fail |
Callable |
returns '' |
Callback when sanitized input length ≠ 14; return value is used as result |
Generator options
When calling generate(options=None, …), all options are optional:
| Option | Type | Default | Description |
|---|---|---|---|
format |
bool |
False |
When True, return the generated CNPJ in standard format (00.000.000/0000-00) |
prefix |
str |
'' |
Partial start string (0–12 alphanumeric chars). Missing characters are generated and check digits computed. |
type |
'numeric' | 'alphabetic' | 'alphanumeric' |
'alphanumeric' |
Character set for the randomly generated part. Check digits are always numeric. |
Prefix rules: base ID (first 8 chars) and branch ID (chars 9–12) cannot be all zeros; 12 repeated digits (e.g. 111111111111) are also not allowed.
Validator options
When calling is_valid(cnpj_input, options=None, …), all options are optional:
| Option | Type | Default | Description |
|---|---|---|---|
case_sensitive |
bool |
True |
When False, lowercase letters are accepted for alphanumeric CNPJ (input is uppercased before validation). |
type |
'numeric' | 'alphanumeric' |
'alphanumeric' |
'numeric': only digits (0–9); 'alphanumeric': digits and letters (0–9, A–Z). |
cnpj_utils (default instance)
The module-level cnpj_utils is a pre-built CnpjUtils instance. Use it for quick one-off calls:
format(cnpj_input, options=None, …): Formats a CNPJ string or sequence of strings. Delegates to the internal formatter. Input must be 14 alphanumeric characters (after sanitization); otherwiseon_failis used.generate(options=None, …): Generates a valid CNPJ. Delegates to the internal generator.is_valid(cnpj_input, options=None, …): ReturnsTrueif the CNPJ is valid. Delegates to the internal validator.
CnpjUtils (class)
For custom default formatter, generator, or validator, create your own instance:
from cnpj_utils import CnpjUtils
utils = CnpjUtils(
formatter={'hidden': True, 'hidden_key': '#'},
generator={'type': 'numeric', 'format': True},
validator={'type': 'numeric', 'case_sensitive': False},
)
utils.format('RK0CMT3W000100') # 'RK.0CM.###/####-##'
utils.generate() # e.g. '73.008.535/0005-06'
utils.is_valid('98.765.432/0001-98') # True
# Access or replace internal instances
utils.formatter # CnpjFormatter
utils.generator # CnpjGenerator
utils.validator # CnpjValidator
__init__(*, formatter=None, generator=None, validator=None): Each keyword may be an options mapping, aCnpjFormatterOptions/CnpjGeneratorOptions/CnpjValidatorOptionsinstance (stored by reference — mutating it later affects subsequent calls with no per-call override), a component instance, or omitted for defaults. PassingNonefor a component creates a new instance with default options.format(cnpj_input, options=None, …): Same as the default instance; per-call options override the formatter's defaults for that call only.generate(options=None, …): Same as the default instance; per-call options override the generator's defaults.is_valid(cnpj_input, options=None, …): Same as the default instance; per-call options override the validator's defaults.formatter,generator,validator: Properties with getters and setters for the internal formatter, generator, and validator. Setters accept the same shapes as the constructor. To change a single option without replacing the instance, mutate the component's options (e.g.utils.formatter.options.hidden = True).
Instance defaults and per-call overrides:
utils = CnpjUtils(
formatter={'hidden': True, 'hidden_key': '#'},
generator={'format': True},
validator={'type': 'numeric'},
)
cnpj = '03603568000195'
utils.format(cnpj) # masked (instance formatter defaults)
utils.format(cnpj, hidden=False) # this call only: unmasked
utils.generate(format=False) # this call only: compact output
utils.is_valid('1QB5UKALPYFP59') # False (instance validator is numeric-only)
utils.is_valid( # True for this call
'1QB5UKALPYFP59',
type='alphanumeric',
)
Options can also be passed as a mapping on each method:
utils.format(cnpj, {'slash_key': '|'})
utils.generate({'prefix': '12345', 'type': 'numeric'})
utils.is_valid('1QB5UKALPYFP59', {'case_sensitive': False})
Using the underlying helpers and classes
You can use the re-exported formatter, generator, and validator directly:
from cnpj_utils import (
cnpj_fmt,
CnpjFormatter,
cnpj_gen,
CnpjGenerator,
cnpj_val,
CnpjValidator,
)
cnpj_fmt('01ABC234000X56', slash_key='|') # '01.ABC.234|000X-56'
cnpj_gen(type='numeric') # e.g. '65453043000178'
cnpj_val('9JN7MGLJZXIO50') # True
formatter = CnpjFormatter({'hidden': True})
formatter.format('AB123XYZ000123') # 'AB.123.***/****-**'
See cnpj-fmt, cnpj-gen, and cnpj-val for full option and error details.
API
Exports
cnpj_utils: Pre-builtCnpjUtilsinstance withformat,generate, andis_valid.CnpjUtils: Class to create a utils instance with optional default formatter, generator, and validator settings.- Formatter:
cnpj_fmt,CnpjFormatter,CnpjFormatterOptions, and formatter exceptions (see cnpj-fmt). - Generator:
cnpj_gen,CnpjGenerator,CnpjGeneratorOptions, and generator exceptions (see cnpj-gen). - Validator:
cnpj_val,CnpjValidator,CnpjValidatorOptions, and validator exceptions (see cnpj-val).
Errors & Exceptions
CnpjUtils does not define its own exception types; it propagates errors from the bundled packages:
- Formatting:
CnpjFormatterInputTypeError,CnpjFormatterOptionsTypeError,CnpjFormatterOptionsHiddenRangeInvalidException,CnpjFormatterOptionsForbiddenKeyCharacterException, and related classes. - Generation:
CnpjGeneratorOptionsTypeError,CnpjGeneratorOptionPrefixInvalidException,CnpjGeneratorOptionTypeInvalidException, and related classes. - Validation:
CnpjValidatorInputTypeError,CnpjValidatorOptionsTypeError,CnpjValidatorOptionTypeInvalidException, and related classes.
Invalid option types are TypeError subclasses; invalid option values are Exception subclasses. Validation failure returns False; formatting length failure is handled by on_fail (default returns an empty string).
from cnpj_utils import CnpjUtils, cnpj_fmt
from cnpj_fmt import CnpjFormatterInputTypeError
from cnpj_val import CnpjValidatorInputTypeError
try:
CnpjUtils().format(12345)
except CnpjFormatterInputTypeError as e:
print(e)
try:
CnpjUtils().is_valid(12345678000198)
except CnpjValidatorInputTypeError as e:
print(e)
# Custom on_fail for invalid length
def custom_fail(value, exception=None):
return f'Invalid CNPJ: {value}'
cnpj_fmt('123', on_fail=custom_fail) # 'Invalid CNPJ: 123'
cnpj_fmt('123') # '' (default on_fail)
Bundled packages
| Package | Main resources | README |
|---|---|---|
cnpj-fmt |
CnpjFormatter, CnpjFormatterOptions, cnpj_fmt() |
docs |
cnpj-gen |
CnpjGenerator, CnpjGeneratorOptions, cnpj_gen() |
docs |
cnpj-val |
CnpjValidator, CnpjValidatorOptions, cnpj_val() |
docs |
All of the above are pulled in as dependencies of cnpj-utils. For exhaustive option tables, exception lists, and edge-case behavior, see each package README.
Contribution & Support
We welcome contributions! Please see our Contributing Guidelines for details. If you find this project helpful, please consider:
- ⭐ Starring the repository
- 🤝 Contributing to the codebase
- 💡 Suggesting new features
- 🐛 Reporting bugs
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
Built Distribution
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
File details
Details for the file cnpj_utils-2.0.2.tar.gz.
File metadata
- Download URL: cnpj_utils-2.0.2.tar.gz
- Upload date:
- Size: 15.6 kB
- Tags: Source
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.2.0 CPython/3.14.6
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
3ea12f87511b994cb424fbdd4fd5551c8cd5562afdfd18dd47a1d9959cf07634
|
|
| MD5 |
f4d2ff963bcb300041f015f48a062b13
|
|
| BLAKE2b-256 |
27e4eddca1d05ecd95a87ca77e7d0280f178fd377d99bf7504b6210cfee6a18e
|
File details
Details for the file cnpj_utils-2.0.2-py3-none-any.whl.
File metadata
- Download URL: cnpj_utils-2.0.2-py3-none-any.whl
- Upload date:
- Size: 11.0 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.2.0 CPython/3.14.6
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
f42f32ef2e02cb89dcf5a7552e6ee354911fbdb69fae688857159bbdd6bf5106
|
|
| MD5 |
49353b09f0745b417b70fac77b34b04e
|
|
| BLAKE2b-256 |
c35c88e132d9498975b2434535695949afc2b6b2648752bf1ad702fbe841ece8
|