Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is everything in Python castable to a string?

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?

like image 896
sneilan Avatar asked Mar 16 '26 00:03

sneilan


1 Answers

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.

like image 128
tdelaney Avatar answered Mar 17 '26 13:03

tdelaney



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!