@@ -215,13 +215,18 @@ def is_valid(cnpj: str) -> bool:
215215 return isinstance (cnpj , str ) and validate (cnpj )
216216
217217
218- def generate (branch : int = 1 ) -> str :
218+ def generate (branch : int | str = 1 , alphanumeric : bool = False ) -> str :
219219 """
220- Generates a random valid CNPJ digit string. An optional branch number
221- parameter can be given; it defaults to 1.
220+ Generates a random valid CNPJ string. An optional branch number parameter
221+ can be given; it defaults to 1. Use alphanumeric=True to generate a CNPJ
222+ whose first 12 characters may contain digits and uppercase letters.
222223
223224 Args:
224- branch (int): An optional branch number to be included in the CNPJ.
225+ branch (int | str): An optional branch number to be included in the
226+ CNPJ. Alphanumeric branch values are accepted only with
227+ alphanumeric=True.
228+ alphanumeric (bool): Whether the generated CNPJ should be
229+ alphanumeric.
225230
226231 Returns:
227232 str: A randomly generated valid CNPJ string.
@@ -231,8 +236,23 @@ def generate(branch: int = 1) -> str:
231236 "30180536000105"
232237 >>> generate(1234)
233238 "01745284123455"
239+ >>> generate(branch="AB12", alphanumeric=True)
240+ "NX9K79E2AB1200"
234241 """
235242
243+ if alphanumeric :
244+ branch = str (branch )
245+ branch = branch [:4 ] if len (branch ) >= 4 else branch .zfill (4 )
246+ branch = (
247+ "0001"
248+ if branch == "0000" or not _is_alphanumeric (branch )
249+ else branch
250+ )
251+ base = "" .join (choices (digits * 3 + ascii_uppercase , k = 8 )) + branch
252+
253+ return base + _checksum (base )
254+
255+ branch = int (branch )
236256 branch %= 10000
237257 branch += int (branch == 0 )
238258 branch = str (branch ).zfill (4 )
@@ -241,34 +261,6 @@ def generate(branch: int = 1) -> str:
241261 return base + _checksum (base )
242262
243263
244- def generate_alphanumeric (branch : str = "1" ) -> str :
245- """
246- Generates a random valid alphanumeric CNPJ digit string. An optional branch
247- number parameter can be given; it defaults to '1'.
248-
249- Args:
250- branch (str): An optional branch number to be included in the CNPJ.
251-
252- Returns:
253- str: A randomly generated valid alphanumeric CNPJ string.
254-
255- Example:
256- >>> generate_alphanumeric()
257- "9359QAG9000184"
258- >>> generate_alphanumeric('1234')
259- "NX9K79E2123400"
260- """
261-
262- branch = branch [:4 ] if len (branch ) >= 4 else branch .zfill (4 )
263- branch = (
264- "0001" if branch == "0000" or not _is_alphanumeric (branch ) else branch
265- )
266-
267- base = "" .join (choices (digits * 3 + ascii_uppercase , k = 8 )) + branch
268-
269- return base + _checksum (base )
270-
271-
272264def _hashdigit (cnpj : str , position : int ) -> int :
273265 """
274266 Calculates the checksum digit at the given `position` for the provided
0 commit comments