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)
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)
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With