Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there any object can make str() function throw error or exception in python?

I have a function that requires the input to be a string.

I know I can assert or do check on the input type, but I would like to handle that as much as possible.

I have following code to handle that. But I'm wondering if there's any case that this line can throw exception that I need to handle.

def foo(any_input):
    clean_input = str(any_input) # will this throw any exception or error?
    process(clean_input)
like image 320
Suanmeiguo Avatar asked Nov 05 '15 23:11

Suanmeiguo


2 Answers

Yes, some 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)
like image 135
Martín Muñoz del Río Avatar answered Nov 09 '22 22:11

Martín Muñoz del Río


You might get a RuntimeError while trying to str a deeply-nested list:

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

or a MemoryError trying to str a huge list:

>>> 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
like image 34
nneonneo Avatar answered Nov 09 '22 22:11

nneonneo