🚀 Full support for the new alphanumeric CNPJ format.
A Python utility to format CNPJ (Brazilian Business Tax ID).
Python Support
| Passing ✔ | Passing ✔ | Passing ✔ | Passing ✔ | Passing ✔ |
Features
- ✅ Alphanumeric CNPJ: Supports 14-character alphanumeric CNPJ (digits and letters, e.g.
RK0CMT3W000100) - ✅ Flexible input: Accepts
stror a sequence ofstr; sequence elements are concatenated in order - ✅ Format agnostic: Strips non-alphanumeric characters and uppercases letters before formatting
- ✅ Custom delimiters:
dot_key,slash_key, anddash_keymay be empty, single-, or multi-character strings - ✅ Masking: Optional hiding of a character range with a configurable replacement string (
hidden,hidden_key,hidden_start,hidden_end) - ✅ HTML & URL output: Optional
escape(HTML entities) andencode(URI component encoding, similar to JavaScriptencodeURIComponent) - ✅ Length errors without throwing: Invalid length after sanitization is handled via
on_fail(default returns an empty string) - ✅ Minimal dependencies: Only
lacus.utils - ✅ Error handling: Type errors for wrong API use; option validation via dedicated exception classes
Installation
$ pip install cnpj-fmt
Import
from cnpj_fmt import CnpjFormatter, CnpjFormatterOptions, cnpj_fmt
Quick start
from cnpj_fmt import CnpjFormatter
formatter = CnpjFormatter()
formatter.format('03603568000195') # '03.603.568/0001-95'
formatter.format('12ABC34500DE99') # '12.ABC.345/00DE-99'
formatter.format('RK0CMT3W000100') # 'RK.0CM.T3W/0001-00'
Usage
The main entry points are the class CnpjFormatter, the options class CnpjFormatterOptions, and the helper cnpj_fmt().
CnpjFormatter
-
__init__: Optional default formatting options. The first parameter may beNone, a mapping of option keys, or aCnpjFormatterOptionsinstance (that exact instance is stored; mutating it later affects subsequentformat()calls that do not pass per-call options). You may also pass option fields as keyword arguments (hidden,hidden_key,dot_key, …). Example:CnpjFormatter(hidden=True, slash_key='|'). -
options: Property returning the instance’sCnpjFormatterOptions(same object used internally). -
format(cnpj_input, options=None, …): Formats a CNPJ value.Input is normalized by removing non-alphanumeric characters and uppercasing. If the sanitized length is not exactly 14, the
on_failcallback is invoked with the original input and aCnpjFormatterInputLengthException; its return value is the result (nothing is thrown for length).If the input is not a
stror a sequence ofstr,CnpjFormatterInputTypeErroris raised.Per-call options are merged over the instance defaults for that call only (instance defaults are unchanged). Pass a
CnpjFormatterOptionsinstance or a mapping as the second argument, in addition to keyword arguments; when both are provided, theoptionsargument wins.
CnpjFormatterOptions
Holds all formatter settings, with validation and merge support. Exposes properties: hidden, hidden_key, hidden_start, hidden_end, dot_key, slash_key, dash_key, escape, encode, on_fail.
__init__(options=None, *extra_overrides, hidden=None, hidden_key=None, hidden_start=None, hidden_end=None, dot_key=None, slash_key=None, dash_key=None, escape=None, encode=None, on_fail=None): Optional default options (plain mapping,CnpjFormatterOptionsinstance, or keyword arguments), plus extra override objects merged in order (later overrides win).all: Returns a shallow copy of all current options.copy(): Returns a shallow copy of this options instance.set(options): Updates multiple fields at once; returnsself. Accepts a mapping or anotherCnpjFormatterOptionsinstance.set_hidden_range(hidden_start, hidden_end): Validates indices in[0, 13](inclusive); ifhidden_start > hidden_end, values are swapped.Nonearguments fall back to defaults (DEFAULT_HIDDEN_START/DEFAULT_HIDDEN_END).
hidden_start / hidden_end: Indices refer to the 14-character normalized CNPJ string (before inserting punctuation). The inclusive range is replaced internally by placeholders, then hidden_key is substituted (supports multi-character keys and empty string).
Key options (hidden_key, dot_key, slash_key, dash_key): Must be strings and must not contain any character in CnpjFormatterOptions.DISALLOWED_KEY_CHARACTERS (reserved for internal formatting).
Functional helper
cnpj_fmt() builds a new CnpjFormatter from the same constructor parameters and calls format(cnpj_input) once. Use keyword arguments, a mapping, or a CnpjFormatterOptions instance for options:
from cnpj_fmt import cnpj_fmt
cnpj = '03603568000195'
cnpj_fmt(cnpj) # '03.603.568/0001-95'
cnpj_fmt(cnpj, hidden=True) # masked with defaults
cnpj_fmt( # '03603568|0001_95'
cnpj,
dot_key='',
slash_key='|',
dash_key='_',
)
cnpj_fmt(cnpj, { # mapping form
'hidden': True,
'hidden_key': '#',
})
Object-oriented examples
from cnpj_fmt import CnpjFormatter
formatter = CnpjFormatter()
cnpj = '03603568000195'
formatter.format(cnpj) # '03.603.568/0001-95'
formatter.format( # '03.603.###/####-##'
cnpj,
hidden=True,
hidden_key='#',
hidden_start=5,
hidden_end=13,
)
Default options on the instance; per-call overrides:
formatter = CnpjFormatter(hidden=True)
formatter.format(cnpj) # uses instance masking
formatter.format(cnpj, hidden=False) # this call only: unmasked
formatter.format(cnpj) # back to instance defaults
Alphanumeric input and sequence input:
formatter.format('RK0CMT3W000100') # 'RK.0CM.T3W/0001-00'
formatter.format([ # 'RK.0CM.T3W/0001-00'
'RK',
'0CM',
'T3W',
'0001',
'00',
])
Input formats
String: Raw digits and/or letters, or already formatted CNPJ (e.g. 12.345.678/0009-10, 12.ABC.345/00DE-99). Non-alphanumeric characters are removed; lowercase letters are uppercased.
Sequence of strings: Each element must be a str; values are concatenated (e.g. per digit, grouped segments, or mixed with punctuation — all are stripped during normalization). Non-string elements are not allowed.
Formatting options
| Parameter | Type | Default | Description |
|---|---|---|---|
hidden |
bool | None |
False |
When True, replaces the inclusive index range [hidden_start, hidden_end] on the normalized 14-character string before punctuation is applied |
hidden_key |
str | None |
'*' |
Replacement for each hidden position (may be multi-character or empty); must not use disallowed key characters |
hidden_start |
int | None |
5 |
Start index 0–13 (inclusive) |
hidden_end |
int | None |
13 |
End index 0–13 (inclusive); if hidden_start > hidden_end, they are swapped |
dot_key |
str | None |
'.' |
Separator between groups XX / XXX / XXX |
slash_key |
str | None |
'/' |
Separator before the branch block |
dash_key |
str | None |
'-' |
Separator before the last two characters |
escape |
bool | None |
False |
When True, HTML-escapes the final string |
encode |
bool | None |
False |
When True, URL-encodes the final string (similar to encodeURIComponent) |
on_fail |
Callable | None |
see below | (value, exception) -> str — used when sanitized length ≠ 14 |
Default on_fail returns an empty string. The exception passed for length failures is CnpjFormatterInputLengthException (actual_input, evaluated_input, expected_length).
Example with all options:
from cnpj_fmt import cnpj_fmt
cnpj = '03603568000195'
cnpj_fmt(
cnpj,
hidden=True,
hidden_key='#',
hidden_start=5,
hidden_end=11,
dot_key=' ',
slash_key='|',
dash_key='_-_',
escape=True,
encode=True,
on_fail=lambda value, exception: str(value),
)
Errors & exceptions
- Wrong input type (not
stror a sequence ofstr):CnpjFormatterInputTypeError— extendsCnpjFormatterTypeError(extends built-inTypeError). - Invalid option types or values when constructing or merging options:
CnpjFormatterOptionsTypeError,CnpjFormatterOptionsHiddenRangeInvalidException,CnpjFormatterOptionsForbiddenKeyCharacterException— extendCnpjFormatterTypeErrororCnpjFormatterExceptionas appropriate.
Length mismatch does not throw from format(); handle it inside on_fail.
from cnpj_fmt import (
CnpjFormatter,
CnpjFormatterInputLengthException,
CnpjFormatterInputTypeError,
)
try:
CnpjFormatter().format(12345)
except CnpjFormatterInputTypeError as e:
e # handle type error
CnpjFormatter().format(
'short',
on_fail=lambda value, exception: 'invalid',
) # 'invalid'
API
Exports
All public symbols are available from the cnpj_fmt package:
cnpj_fmt:(cnpj_input: CnpjInput, options=None, **kwargs) -> str— convenience helper.CnpjFormatter: Class to format CNPJ with optional default options; acceptsCnpjInputinformat().CnpjFormatterOptions: Class holding options; supports merge via constructor,set(), and keyword arguments.CNPJ_LENGTH:14(constant).CnpjInput: Type alias —str | Sequence[str].- Exceptions:
CnpjFormatterTypeError,CnpjFormatterInputTypeError,CnpjFormatterOptionsTypeError,CnpjFormatterException,CnpjFormatterInputLengthException,CnpjFormatterOptionsHiddenRangeInvalidException,CnpjFormatterOptionsForbiddenKeyCharacterException.
Other available resources
CnpjFormatterOptions.CNPJ_LENGTH:14.CnpjFormatterOptions.DISALLOWED_KEY_CHARACTERS: Characters forbidden inhidden_key,dot_key,slash_key,dash_key.CnpjFormatterOptions.DEFAULT_*: Default values for each option.
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
Metadata
Release files for cnpj-fmt 2.0.2
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Source distribution (sdist)
| File | Size | Uploaded | Provenance | Actions |
|---|---|---|---|---|
| cnpj_fmt-2.0.2.tar.gz | 20.1 kB | Without provenance | Details for cnpj_fmt-2.0.2.tar.gz |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Actions Reset |
|---|---|---|---|---|
| cnpj_fmt-2.0.2-py3-none-any.whl | Python 3 | none | any | Details for cnpj_fmt-2.0.2-py3-none-any.whl |
Total release size: 38.7 kB
Release files / cnpj_fmt-2.0.2.tar.gz
| Download URL | cnpj_fmt-2.0.2.tar.gz |
|---|---|
| Size | 20.1 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
c812b9ecdb74d808a6b8becae7c88763fac17bbe6623fb5d8acaf1f426e63eba
|
|
BLAKE2b-256 checksum How to use checksums |
36aa3e478678be716ce78e5d655d9ff9ecb7c0d3769353500f03ef6a0ddf1813
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
twine/6.2.0 CPython/3.14.6
|
Release files / cnpj_fmt-2.0.2-py3-none-any.whl
| Download URL | cnpj_fmt-2.0.2-py3-none-any.whl |
|---|---|
| Size | 18.6 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
e5bb132dda73859625cc30141d76ad888ee5739910e2c75cfd086d0cff11f293
|
|
BLAKE2b-256 checksum How to use checksums |
261b4ad9145f68ac5d5e73ad767445621cde7cb6e127b74b4aa61560cda235a6
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
twine/6.2.0 CPython/3.14.6
|
Security for cnpj-fmt 2.0.2
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
No provenance found
None of the files in this release were uploaded with provenance metadata.
A note on package security
PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.
To learn more about protecting yourself from malicious actors, visit our package security documentation.