Coverage for /pythoncovmergedfiles/medio/medio/usr/local/lib/python3.11/site-packages/validators/uuid.py: 93%
Shortcuts on this page
r m x toggle line displays
j k next/prev highlighted chunk
0 (zero) top of page
1 (one) first highlighted chunk
Shortcuts on this page
r m x toggle line displays
j k next/prev highlighted chunk
0 (zero) top of page
1 (one) first highlighted chunk
1"""UUID."""
3# standard
4import re
5from typing import Union
6from uuid import UUID
8# local
9from .utils import validator
12@validator
13def uuid(value: Union[str, UUID], /):
14 """Return whether or not given value is a valid UUID-v4 string.
16 This validator is based on [WTForms UUID validator][1].
18 [1]: https://github.com/wtforms/wtforms/blob/master/src/wtforms/validators.py#L539
20 Examples:
21 >>> uuid('2bc1c94f-0deb-43e9-92a1-4775189ec9f8')
22 True
23 >>> uuid('2bc1c94f 0deb-43e9-92a1-4775189ec9f8')
24 ValidationError(func=uuid, args={'value': '2bc1c94f 0deb-43e9-92a1-4775189ec9f8'})
26 Args:
27 value:
28 UUID string or object to validate.
30 Returns:
31 (Literal[True]): If `value` is a valid UUID.
32 (ValidationError): If `value` is an invalid UUID.
33 """
34 if not value:
35 return False
36 if isinstance(value, UUID):
37 return True
38 try:
39 return UUID(value) or re.match(
40 r"^[0-9a-fA-F]{8}-([0-9a-fA-F]{4}-){3}[0-9a-fA-F]{12}$", value
41 )
42 except ValueError:
43 return False