我有一个需要输入为字符串的函数。
我知道我可以断言或检查输入类型,但我想尽可能地处理它。
我有以下代码来处理它。但是我想知道这条线是否会抛出我需要处理的异常。
def foo(any_input):
clean_input = str(any_input) # will this throw any exception or error?
process(clean_input)
答案 0 :(得分:5)
是的,有些unicodes:
>>> str(u'í')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
UnicodeEncodeError: 'ascii' codec can't encode character u'\xed' in position 0: ordinal not in range(128)
答案 1 :(得分:4)
我的意思是,你可以轻而易举地制作一个:
class BadStr:
def __str__(self):
raise Exception("Nope.")
答案 2 :(得分:2)
尝试RuntimeError
深层嵌套列表时,您可能会获得str
:
>>> x = []
>>> for i in range(100000):
... x = [x]
...
>>> y = str(x)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
RuntimeError: maximum recursion depth exceeded while getting the repr of a list
或MemoryError
尝试str
一个巨大的列表:
>>> x = 'a'*1000000
>>> y = [x] * 1000000 # x and y only require a few MB of memory
>>> str(y) # but str(y) requires about a TB of memory
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
MemoryError