8000 1541 UUID bytes support for 16 byte strings / BINARY(16) (#1542) · ag-python/pydantic@4f9e77d · GitHub
[go: up one dir, main page]

Skip to content
files changed
+9
-2
lines changed

4 files changed

+9
-2
lines changed

changes/1541-shawnwall.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
Added support for UUID instantiation through 16 byte strings such as `b'\x12\x34\x56\x78' * 4`. This was done to support `BINARY(16)` columns in sqlalchemy.

docs/usage/types.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -145,7 +145,7 @@ with custom properties and validation.
145145
see [Pydantic Types](#pydantic-types) for other more strict path types
146146

147147
`uuid.UUID`
148-
: strings and bytes (converted to strings) are passed to `UUID(v)`;
148+
: strings and bytes (converted to strings) are passed to `UUID(v)`, with a fallback to `UUID(bytes=v)` for `bytes` and `bytearray`;
149149
see [Pydantic Types](#pydantic-types) for other stricter UUID types
150150

151151
`ByteSize`

pydantic/validators.py

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -260,7 +260,12 @@ def uuid_validator(v: Any, field: 'ModelField') -> UUID:
260260
if isinstance(v, str):
261261
v = UUID(v)
262262
elif isinstance(v, (bytes, bytearray)):
263-
v = UUID(v.decode())
263+
try:
264+
v = UUID(v.decode())
265+
except ValueError:
266+
# 16 bytes in big-endian order as the bytes argument fail
267+
# the above check
268+
v = UUID(bytes=v)
264269
except ValueError:
265270
raise errors.UUIDError()
266271

tests/test_types.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -392,6 +392,7 @@ def __bool__(self) -> bool:
392392
('uuid_check', 'ebcdab58-6eb8-46fb-a190-d07a33e9eac8', UUID('ebcdab58-6eb8-46fb-a190-d07a33e9eac8')),
393393
('uuid_check', UUID('ebcdab58-6eb8-46fb-a190-d07a33e9eac8'), UUID('ebcdab58-6eb8-46fb-a190-d07a33e9eac8')),
394394
('uuid_check', b'ebcdab58-6eb8-46fb-a190-d07a33e9eac8', UUID('ebcdab58-6eb8-46fb-a190-d07a33e9eac8')),
395+
('uuid_check', b'\x12\x34\x56\x78' * 4, UUID('12345678-1234-5678-1234-567812345678')),
395396
('uuid_check', 'ebcdab58-6eb8-46fb-a190-', ValidationError),
396397
('uuid_check', 123, ValidationError),
397398
('decimal_check', 42.24, Decimal('42.24')),

0 commit comments

Comments
 (0)
0