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

Sua*_*guo 3 python string exception

我有一个函数,要求输入是一个字符串.

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

我有以下代码来处理它.但我想知道是否有任何情况,这一行可以抛出我需要处理的异常.

def foo(any_input):
    clean_input = str(any_input) # will this throw any exception or error?
    process(clean_input)
Run Code Online (Sandbox Code Playgroud)

nne*_*neo 5

我的意思是,您可以轻松地做到这一点:

class BadStr:
    def __str__(self):
        raise Exception("Nope.")
Run Code Online (Sandbox Code Playgroud)


Mar*_*Río 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)
Run Code Online (Sandbox Code Playgroud)


nne*_*neo 5

您可能需要一段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
Run Code Online (Sandbox Code Playgroud)

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
Run Code Online (Sandbox Code Playgroud)