Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can str raise exception?

Tags:

python

Is there any chance that str can raise exception for non-callable argument ? Apart of custom classes that could override __repr__ for some reason ?

I have some argument on enter of function and if it's not str I am converting it to it. I'm curious if I have to handle exceptions, and if I have to, which ones ? Handling Exception is not good practice but it seems like it's the only way.

Edit: By no-callable I mean that the argument is not executed inside str, like str(get_something_to_convert()). In this example I should handle exceptions in inner function.

like image 491
Dawid Gosławski Avatar asked Sep 15 '25 17:09

Dawid Gosławski


1 Answers

Any class could override __str__ for any reason because str calls __str__, not __repr__, if both are defined. IMHO that is, by itself, enough reason to be prepared to get exceptions.

But a common pitfall for non-English users is Unicode strings with Python 2.x. Just look at the following code:

>>> a = u'\xe9\xe8'
>>> print a
éè
>>> str(a)

Traceback (most recent call last):
  File "<pyshell#6>", line 1, in <module>
    str(a)
UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-1:
 ordinal not in range(128)

So a simple Unicode string containing non-ASCII characters will throw an exception when you call str on it.

It is up to you whether you prefer to handle the exception, or document that the function only accepts arguments that can be directly converted to string with str.

like image 82
Serge Ballesta Avatar answered Sep 18 '25 07:09

Serge Ballesta