[New-bugs-announce] [issue32112] Should uuid.UUID() accept another UUID() instance?
Martijn Pieters
report at bugs.python.org
Wed Nov 22 05:52:36 EST 2017
New submission from Martijn Pieters <mj at python.org>:
When someone accidentally passes in an existing uuid.UUID() instance into uuid.UUID(), an attribute error is thrown because it is not a hex string:
>>> import uuid
>>> value = uuid.uuid4()
>>> uuid.UUID(value)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/Users/mjpieters/Development/Library/buildout.python/parts/opt/lib/python2.7/uuid.py", line 133, in __init__
hex = hex.replace('urn:', '').replace('uuid:', '')
AttributeError: 'UUID' object has no attribute 'replace'
This happened in the Stack Overflow question at https://stackoverflow.com/q/47429929/100297, because the code there didn't take into account that some database drivers may already have mapped the PostgreSQL UUID column to a Python uuid.UUID() object.
The fix could be as simple as:
if hex is not None:
if isinstance(hex, uuid.UUID):
int = hex.int
else:
hex = hex.replace('urn:', '').replace('uuid:', '')
hex = hex.strip('{}').replace('-', '')
if len(hex) != 32:
raise ValueError('badly formed hexadecimal UUID string')
int = int_(hex, 16)
Or we could add a uuid=None keyword argument, and use
if hex is not None:
if isinstance(hex, uuid.UUID):
uuid = hex
else:
hex = hex.replace('urn:', '').replace('uuid:', '')
hex = hex.strip('{}').replace('-', '')
if len(hex) != 32:
raise ValueError('badly formed hexadecimal UUID string')
int = int_(hex, 16)
if uuid is not None:
int = uuid.int
----------
messages: 306719
nosy: mjpieters
priority: normal
severity: normal
status: open
title: Should uuid.UUID() accept another UUID() instance?
_______________________________________
Python tracker <report at bugs.python.org>
<https://bugs.python.org/issue32112>
_______________________________________
More information about the New-bugs-announce
mailing list