在 Python 中使用 int
和 float
等内置类型时,通常在输入可能不可靠的情况下使用异常处理:
def friendly_int_convert(val):
"Convert value to int or return 37 & print an alert if conversion fails"
try:
return int(val)
except ValueError:
print('Sorry, that value doesn\'t work... I chose 37 for you!')
return 37
使用 str()
时是否需要注意任何突出的边缘情况?
def friendly_str_convert(val):
"Convert value to str or return 'yo!' & print an alert if conversion fails"
try:
return str(val)
except Exception: # Some specific Exception here
print('Sorry, that value doesn\'t work... I chose \'yo!\' for you!')
return 'yo!'
我真的不喜欢使用宽泛的 Exception
,因为有像 NameError
这样的情况表明代码有问题,应该引发错误。我已经将 UnicodeError
视为候选对象,但我不确定 str()
是否会导致它(与 foo.encode()
和foo.decode()
,它更容易理解)并且会喜欢什么输入的例子,如果有的话,会触发它。
总结:即使输入不可靠,在没有 try
/except
block 的情况下使用 str()
通常是否安全?
最佳答案
In summary: Is it generally safe to use
str()
without atry
/except
block even with unreliable input?
这取决于我们谈论的是哪种输入。您已将此问题标记为 Python 3,因此您无需担心使用 Python 2 和 Unicode 输入时出现的 UnicodeEncodeErrors,但您收到的对象可以在其 __str__< 中执行几乎所有操作
或 __repr__
,引发几乎任何类型的异常。例如,
In [18]: import weakref
In [19]: class Foo(object): pass
In [20]: str(weakref.proxy(Foo()))
---------------------------------------------------------------------------
ReferenceError Traceback (most recent call last)
<ipython-input-20-396b2ab40052> in <module>()
----> 1 str(weakref.proxy(Foo()))
ReferenceError: weakly-referenced object no longer exists
关于python - 在 Python 中使用内置 str() 类型的潜在异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38380335/