是否有任何对象可以使str()函数在python中抛出错误或异常?

时间:2015-11-05 23:02:15

标签: python string exception

我有一个需要输入为字符串的函数。

我知道我可以断言或检查输入类型,但我想尽可能地处理它。

我有以下代码来处理它。但是我想知道这条线是否会抛出我需要处理的异常。

def foo(any_input):
    clean_input = str(any_input) # will this throw any exception or error?
    process(clean_input)

3 个答案:

答案 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