Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can a conversion to string raise an error? [duplicate]

I was wondering if converting to string i.e. str(sth) can raise an exception like for example float(sth) does? I am asking this to know if it is necessary to wrap my code in:

try:     x = str(value) except ValueError:     x = None 

to be sure that execution does not stop because of conversion failure.

Also does this differ in Python 2 and 3, since the str class is different in them??

like image 625
S.Mohsen sh Avatar asked Aug 16 '16 12:08

S.Mohsen sh


1 Answers

If you encounter a custom class that explicitly raises an exception in __str__ (or __repr__ if __str__ is not defined). Or, for example a class that returns a bytes object from __str__:

class Foo:     def __str__(self):         return b''  str(Foo()) # TypeError: __str__ returned non-string (type bytes) 

But personally, I have never seen this and I'm pretty sure no one has; it would be daft to do it. Likewise, a silly mistake in the implementation of __str__ or edge cases might create another Exception. It is interesting to see how you could push Python to these edge cases (look at @user2357112 answer here).

Other than that case, no built-ins generally raise an exception in this case since it is defined for all of them in Py2 and Py3.

For user defined classes str will use object.__str__ by default if not defined in Python 3 and, in Python 2, use it if a class is a new style class (inherits from object).

If a class is an old style class I believe it is classobj.__str__ that is used for classes and instance.__str__ for instances.

In general, I would not catch this, special cases aren't special enough for this.

like image 159
Dimitris Fasarakis Hilliard Avatar answered Sep 20 '22 07:09

Dimitris Fasarakis Hilliard