New submission from Martijn Pieters <m...@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 <rep...@bugs.python.org>
<https://bugs.python.org/issue32112>
_______________________________________
_______________________________________________
Python-bugs-list mailing list
Unsubscribe: 
https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com

Reply via email to