1

Validating a uuid4 with Python.

 1 week ago
source link: https://gist.github.com/ShawnMilo/7777304
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

Validating a uuid4 with Python. · GitHub

Instantly share code, notes, and snippets.

Created December 3, 2013 20:55
Clone this repository at <script src="https://gist.github.com/ShawnMilo/7777304.js"></script>
Save ShawnMilo/7777304 to your computer and use it in GitHub Desktop.
Validating a uuid4 with Python.

so str(uuid.uuid4()) returns b514af82-3c4f-4bb5-b1da-a89a0ced5e6f, however this is not the same as the hex version. so using the following test code will not work.

    assert validate_uuid4(uuid.uuid4())

craig8 is right, I just changed the last function line with:

return val.hex == uuid_string.replace('-', '')

and now it works

A ValueError is not the only type of exception UUID can throw. For example, if you try UUID(0), it will produce an AttributeError. Assuming you want the function to return False in this case (since 0 is clearly not a valid UUID4), you could consider replace except ValueError with except Exception.

@khpeek you are right but in his function he explicitly expects a string

I think val == UUID(uuid_string) would work the best. No need to get .hex() or do any string replacements. The reason to use UUID(uuid_string) without the version kwarg is so it would work with the other formats UUID allows too like curly braces and urn prefixes. These extraneous parts of the string are removed by UUID.init().

val is possibly converted to uuid4.
UUID(uuid_string) is just the hex string as is with no conversion.

I guess this gist just expects only hex strings as input.

I would just replace the return val.hex == uuid_string with return str(val) == uuid_string

would it make sense to .lower() the string before comparing it? (just in case)

@apostolos Sure, validators typical tell you whether and object passes some criteria; cleaning or scrubbing your inputs is where you massage things to give the user a break on things like capitalization. Then you validate the massaged version.


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK