[Python-ideas] Dunder method to make object str-like
Paul Moore
p.f.moore at gmail.com
Thu Apr 7 12:11:25 EDT 2016
On 7 April 2016 at 16:49, Chris Angelico <rosuav at gmail.com> wrote:
> 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).
OK, that makes sense. But when you say "it'll work fine in Python 3"
how will that happen? What code needs to call __fromstring__ to make
this happen? You mention getattr. Would you expect every builtin and
stdlib function that takes a string to be modified to try
__fromstring__? That sounds like a pretty big performance hit, as
strings are very critical to the interpreter.
Even worse, what should open() do? It takes a string as an argument.
To support patthlib, it needs to also call __fspath__. I presume you'd
also want it to call __fromstring__ so that your Ascii class could be
used as an argument to open as well. This is starting to seem
incredibly messy to solve a problem that's basically about extending
support for Python 2, which is explicitly not something the Python 3
core should be doing...
Paul
More information about the Python-ideas
mailing list