[Python-ideas] Dunder method to make object str-like
ethan at stoneleaf.us
Thu Apr 7 12:32:42 EDT 2016
On 04/07/2016 08:49 AM, Chris Angelico wrote:
> On Fri, Apr 8, 2016 at 1:43 AM, Ethan Furman 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).
Make the Ascii class subclass bytes in 2.x and str in 3.x; the 2.x
version's __str__ returns bytes, while it's __unicode__ returns unicode
and in 3.x __str__returns str, and __unicode__ doesn't exist.
Problem solved, no other special methods needed.* ;)
* crosses fingers hoping to not have missed something obvious ;)
More information about the Python-ideas