Any other input type (e.g. a float or a list) raises a TypeError, since
that usually signals a problem in the data pipeline that is better
surfaced early than hidden by a False return. The formatting, padding,
and parsing functions raise TypeError for missing values too, because
there is no sensible way to format or parse a missing identifier. This
behavior is shared by all validation functions in the package as of
version 0.10.0.
Validate a CEI number, used for businesses that do not require a CNPJ:
The first 8 digits of CNPJs identify a firm, and the following 4 digits
identify a specific business establishment owned by that firm. Headquarters is
often establishment 0001. The cnpj_from_firm_id function will create a
full CNPJ from the first 8 digits and a given establishment number:
Alphanumeric CNPJs are parsed the same way. Since letters can't be
represented as Python ints, formatted=False returns strings for the
identifier components; the check digits are always numeric, so they are
returned as integers in both cases:
Note: as alphanumeric CNPJs become more common, a future release may
switch parse_cnpj(..., formatted=False) to returning strings for all
CNPJs, so avoid relying on the integer representation in new code.
CEP Parsing
Códigos de Endereçamentos Postais (zip codes) can be formatted and parsed:
Validation of IBGE município (municipal) identifiers is also possible:
>>> from brazilnum.muni import validate_muni
>>> validate_muni(3550308) # São Paulo
True
>>> validate_muni(4305871) # Coronel Barros (see note below)
True
Note that 9 true codes do not follow the correct verification pattern. ENCAT
has a technical note
about this issue. The program correctly handles special codes like Coronel
Barros, RS (see above).
If you need random CNPJ for database testing, use the random_cnpj function,
which can return either unformatted or formatted identifiers:
from brazilnum.cnpj import random_cnpj
random_cnpj() # for a random, formatted CNPJ
random_cnpj(False) # for a random, unformatted CNPJ
random_cnpj(alphanumeric=True) # for a random alphanumeric CNPJ
Use random_cei for random CEI identifiers:
from brazilnum.cei import random_cei
random_cei()
The same thing exists for PIS/PASEP and CPF identifiers:
from brazilnum.pis import random_pis
random_pis()
from brazilnum.cpf import random_cpf
random_cpf()
Check Digits
If you're interested in the check digits, there are functions for
calculating them that return integers:
>>> from brazilnum.cnpj import cnpj_check_digits
>>> cnpj_check_digits('02.558.157/0001-62')
(6, 2)
>>> from brazilnum.cei import cei_check_digit
>>> cei_check_digit('11.583.00249/85')
5
>>> from brazilnum.cpf import cpf_check_digits
>>> cpf_check_digits('041.936.758-66')
(6, 6)
>>> from brazilnum.pis import pis_check_digit
>>> pis_check_digit('125.6124.131-0')
0
CNPJ check digits are calculated from the first 12 digits: