How to check UUID validity in Python?

Viewed 7033

I have a string that should be a UUID. Is there any built-in Python function available to check whether the UUID is valid or not, and to check its version?

1 Answers

To check the validity of a UUID string, simply try to create a new uuid object with it. If it's invalid...

uuid.UUID("foo")
# => ValueError: badly formed hexadecimal UUID string

If you need to know the version of the UUID, it's right there in the UUID API:

uuid.UUID('302a4299-736e-4ef3-84fc-a9f400e84b24').version
# => 4
Related