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

Chris Angelico rosuav at gmail.com
Thu Apr 7 14:28:35 EDT 2016


On Fri, Apr 8, 2016 at 3:31 AM, Brett Cannon <brett at python.org> wrote:
> But couldn't you also just define a str subclass that checks its argument(s)
> are only valid ASCII values? What you're proposing is to potentially change
> all places that operate with a string to now check for a special method
> which would be a costly change potentially to performance as well as
> propagating this concept everywhere a string-like object is expected.

Fair enough. That was a spur-of-the-moment thought. To be honest, this
proposal is a massive generalization from, ultimately, a single
use-case.

> I think it's important to realize that the main reason we are considering
> this special method concept is to make it easier to introduce in third-party
> code which doesn't have pathlib or for people who don't want to import
> pathlib just to convert a pathlib.PurePath object to a string.

And this should make it easier for third-party code to be functional
without even being aware of the Path object. There are two basic
things that code will be doing with paths: passing them unchanged to
standard library functions (eg open()), and combining them with
strings. The first will work by definition; the second will if paths
can implicitly upcast to strings.

In contrast, a function or method to convert a path to a string
requires conscious effort on the part of any function that needs to do
such manipulation, which correspondingly means version compatibility
checks. Libraries will need to release a new version that's
path-compatible, even though they don't actually gain any
functionality.

ChrisA


More information about the Python-ideas mailing list