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

Chris Angelico rosuav at gmail.com
Thu Apr 7 11:49:15 EDT 2016

On Fri, Apr 8, 2016 at 1:43 AM, Ethan Furman <ethan at stoneleaf.us> wrote:
> The problem with that is that Paths are conceptually not strings, they just
> serialize to strings, and we have a lot of infrastructure in place to deal
> with that serialized form.
> Is there anything, anywhere in the Python ecosystem, that would also benefit
> from something like an __as_str__ method/attribute?

I'd like to see this used in 2/3 compatibility code. You can make an
Ascii class which subclasses bytes, but can be treated as
str-compatible in both versions. By restricting its contents to
[0,128) it can easily be "safe" in both byte and text contexts, and
it'll cover 99%+ of use cases. So if you try to getattr(x,
Ascii("foo")), it'll work fine in Py2 (because Ascii is a subclass of
str) and in Py3 (because Ascii.__tostring__ returns a valid string),
and there's a guarantee that it'll behave the same way (because the
string must be ASCII-only).


More information about the Python-ideas mailing list