harmful str(bytes)

Stefan Behnel stefan_ml at behnel.de
Tue Oct 12 02:45:24 EDT 2010


Hallvard B Furuseth, 11.10.2010 23:45:
> If there were a __plain_str__() method which was supposed to fail rather
> than start to babble Python syntax, and if there were not plenty of
> Python code around which invoked __str__, I'd agree.

Yes, calling str() "just in case" has a clear code smell. I think that's 
one of the reasons why b'abc' was chosen as output of bytes.__str__, to 
make it clearly visible a) what the type of the value is, e.g. in an 
interactive session, and b) that this wasn't the intended operation if it 
happened during string interpolation etc. and that the user code needs 
fixing. After all, you were complaining about a clearly visible problem (in 
urlunparse) that was easy to find given the incorrect output.

I think raising an exception in bytes.__str__ would be a horrible thing to 
do. That would make it really hard and dangerous to look at bytes objects 
in a debugger or interpreter session. I think the current way bytes.__str__ 
behaves is a good tradeoff between safety and usability, and the output is 
also very clear and readable.

Stefan




More information about the Python-list mailing list