Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python uuid4, How to limit the length of Unique chars

Tags:

python

In Python, I am using uuid4() method to create a unique char set. But I can not find a way to limit that to 10 or 8 characters. Is there any way?

uuid4()

ffc69c1b-9d87-4c19-8dac-c09ca857e3fc

Thanks.

like image 562
A.J. Avatar asked Jul 17 '14 06:07

A.J.


2 Answers

You can use shortuuid package.

pip install shortuuid

then it would be similar to UUID package.

import shortuuid
shortuuid.uuid()

Output

'vytxeTZskVKR7C7WgdSP3d'

Custom Length UUID

shortuuid.ShortUUID().random(length=22)

Output

'RaF56o2r58hTKT7AYS9doj'

Source - https://pypi.org/project/shortuuid/

like image 165
mohammed_ayaz Avatar answered Sep 28 '22 18:09

mohammed_ayaz


The previous answers do not provide a UUID, either because they truncate the string or because they didn't generate a UUID to begin with. According to the documentation, if you truncate the string "[t]he IDs won’t be universally unique any longer [...]" and the documentation describes ShortUUID().random() to generate a cryptographically secure string instead of a UUID.

However, you can change the UUID length indirectly by changing the number of characters in the alphabet. In the implementation of ShortUUID.encoded_length() you can see that the UUID length is int(math.ceil(16 * math.log(256) / math.log(len(alphabet)))). You can change the alphabet by shortuuid.set_alphabet().

The more characters in the alphabet, the shorter the UUID can be and still be unique.

like image 43
wehnsdaefflae Avatar answered Sep 28 '22 18:09

wehnsdaefflae