将无效参数提供给uuid.UUID()时会发生什么?

时间:2013-03-07 18:02:24

标签: python exception uuid

是否会抛出异常? UUID()是否曾默默失败?是否存在来自

的'myStatus'的任何情况
myStatus = True
myUUID = uuid.UUID( someWeirdValue )
if myUUID == None:
    myStatus = False

会等于假吗?

2 个答案:

答案 0 :(得分:7)

UUID()构造函数会引发TypeErrorValueError,具体取决于传入的内容。

未传入任何hexbytesbytes_lefieldsint选项会引发TypeError,传入无效的值会引发ValueError

>>> uuid.UUID()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/uuid.py", line 129, in __init__
    raise TypeError('need one of hex, bytes, bytes_le, fields, or int')
TypeError: need one of hex, bytes, bytes_le, fields, or int
>>> uuid.UUID('abcd')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/uuid.py", line 134, in __init__
    raise ValueError('badly formed hexadecimal UUID string')
ValueError: badly formed hexadecimal UUID string
>>> uuid.UUID(bytes='abcd')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/uuid.py", line 144, in __init__
    raise ValueError('bytes is not a 16-char string')
ValueError: bytes is not a 16-char string

无声地失败。它肯定永远不会返回NonemyUUID设置为UUID实例,或引发异常。

答案 1 :(得分:1)

由于UUID class未覆盖__new__,因此其构造无法返回除uuid.UUID实例以外的任何内容。

模块提供的UUID工厂,功能uuid1uuid4,可能会有一个导致他们返回None的错误。通过粗略地看一眼他们的implementation来判断,这样的错误似乎不太可能。无论导致您的UUID对象为None的任何错误,uuid模块都不是可靠的罪魁祸首。