[Python-ideas] Dunder method to make object str-like

Stephen J. Turnbull stephen at xemacs.org
Fri Apr 8 01:51:08 EDT 2016


Random832 writes:

 > How about ASCII bytes strings [as a use case]? ;)

Very good point, and not at all funny.

In fact, this is pretty well useless except to try to propagate the
Python 2 model of str as maybe-encoded-maybe-not into Python 3 "when
it's safe".  But that's way less than "99%+" of use cases.  Anything
where you combine it with bytes has to result in bytes, or prepare for
the combining operation to raise if the bytes contain any non-ASCII.
Ditto str.  Either way, you've not really gained much safety for the
programmer, although maybe the user would prefer a crashed program to
corrupt data or mojibake on screen.  But they'd rather the program
worked as intended, so the programmer has to do pretty much the same
amount of thinking and coding around the semantic differences between
Python 2 and Python 3 AFAICS.

The only place I can see this StringableASCIIBytes *frequently* being
really "safe" is scripting where you pass a string literal
representing a path to an os function, or print a string literal.  But
guess what, that already works if you just use a str literal!

I'm also not really sure that, given the flexibility and ubiquity of
string representations, that there really are a lot of use cases whose
use of __lossless_i_promise_str__ are mutually compatible.  Eg, if we
use this for pathlib.Path and for urllib_tng.URL, are those really
compatible in the sense that we're happy handing an urllib_tng.URL to
open() and have it try to operate on that?  If not, we need separate
dunders for this purpose.  And ditto for all those hypothetical future
uses (which are unlikely to be as compatible as filesystem paths and
URIs, or URI paths).



More information about the Python-ideas mailing list