Search code examples
pythonuuid

generate int from a uuid


I would like to generate a "random" int from a given uuid. All I care about is that given the uuid, I will always get the same int.

I'm aware that the range of uuids is much largers than the range of ints in python, so I'm taking the risk of 2 different uuids generating the same int, but it's a risk I'm willing to take.

So my question is what is the best way to generate such int from a given uuid? I know I can just maybe use the uuid as a seed to random() and just generate a random int, but wondered if there is a "cleaner" solution.


Solution

  • You can actually convert uuids to ints on python very easily:

    >>> import uuid
    >>> int(uuid.uuid4())
    101044264907663221935019178350016176435
    

    Yeah, it's a really big number, but hey, it will "never" be repeated and the solution is as clean as it could be.

    Edit: Keep in mind that this is for python 3. On python 2 this also works, BUT, the number you'll obtain will be long instead of int:

    >>> import uuid
    >>> int(uuid.uuid4())
    314613414059294171759586868273801197923L
    >>> type(int(uuid.uuid4()))
    <type 'long'>