向uuid.UUID()传入无效参数会发生什么?

2 投票
2 回答
5749 浏览
提问于 2025-04-17 18:18
myStatus = True
myUUID = uuid.UUID( someWeirdValue )
if myUUID == None:
    myStatus = False

会出现异常吗?UUID()会不会在不发出任何警告的情况下失败?有没有可能在某种情况下,'myStatus'的值会变成False?

2 个回答

1

因为这个UUID没有重写__new__这个方法,所以它创建出来的对象只能是uuid.UUID类型的实例,其他类型是不可能的。

这个模块提供的UUID工厂函数,从uuid1uuid4,理论上可能会有bug,导致它们返回None。不过,简单看一下它们的实现代码,似乎不太可能出现这样的bug。不管是什么原因导致你的UUID对象变成None,这个uuid模块都不太可能是问题的根源。

10

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

等等。

它不会悄悄地失败。它绝对不会返回None。要么myUUID会被设置为一个UUID实例,要么就会引发一个异常。

撰写回答