[Python-ideas] Better stdlib support for Path objects

Chris Angelico rosuav at gmail.com
Tue Oct 7 18:04:05 CEST 2014


On Wed, Oct 8, 2014 at 2:55 AM, Antoine Pitrou <solipsis at pitrou.net> wrote:
>> I like the comparison with __index__. It's up to the class to decide
>> whether it wants to be "truly representable as a string". Command-line
>> arguments probably would be, in some canonical form. Config files
>> probably not, as they need their structure, but if you want your
>> config object to act exactly like a text string, then you define
>> __text__.
>
> And what's the use case that would be fulfilled by this exactly?

You pass a Path object to anything whatsoever. If it wants a Path, it
uses it. As soon as that Path gets picked up by something that was
expecting a string, it'll easily and conveniently coerce to string.
But if you pass something other than a string or string-equivalent,
it'll throw an error rather than calling str() on it.

Where is the definition of "able to convert to str implicitly"?

>>> "asdf"+[1,2,3]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: Can't convert 'list' object to str implicitly

Because this could just call Path.__text__(), get back a string, and use that.

Basically, the use-case is that you could create something that's not
a string, but can be used like a string, and APIs unaware of it don't
need to be made aware of it.

Downside: These "text-aware" objects would require Python 3.whatever,
and would be hard to backport. On older versions, they wouldn't
implicitly become strings.

ChrisA


More information about the Python-ideas mailing list