Is everything in Python castable to a string?

Viewed 371

I'm trying to find an example of something in Python that can't be cast to a string.

>>> str(None)
'None'
>>> str(False)
'False'
>>> str(5)
'5'
>>> str(object)
"<class 'object'>"
>>> class Test:
...     pass
...
>>> str(Test)
"<class '__main__.Test'>"
>>> str(Test())
'<__main__.Test object at 0x7f7e88a13630>'

Is there anything the entire Python universe that cannot be cast to str?

2 Answers

Is everything in Python castable to a string?

Nope!

>>> class MyObject():
...     def __str__(self):
...         raise NotImplementedError("You can't string me!")
...
>>> str(MyObject())
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 3, in __str__
NotImplementedError: You can't string me!

From the __str__ documentation:

The default implementation defined by the built-in type object
calls object.__repr__().

and object.__repr__ prints object name and address (at least in cpython). That's where your output '<__main__.Test object at 0x7f7e88a13630>' comes from. A class would have to override __str__ and raise an exception (or have a bug) to fail. There is little reason to do this and you'd be hard-pressed to find one that wasn't built to purpose.

Related