S.Mohsen sh S.Mohsen sh - 1 year ago 95
Python Question

Can a conversion to string raise an error?

I was wondering if converting to string i.e.

can raise an exception like for example
I am asking this to know if it is necessary to wrap my code in:

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
class is different in them??

Jim Jim
Answer Source

Only if you encounter a custom class that explicitly raises an exception in __str__ (or __repr__ if __str__ is not defined), for example:

class Foo:
    def __str__(self):
        raise ValueError("For some reason")

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__ might create another Exception.

Other than that case, no built-ins can 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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download