[Python-ideas] Better stdlib support for Path objects

Nick Coghlan ncoghlan at gmail.com
Tue Oct 7 16:49:12 CEST 2014


On 8 October 2014 00:40, Nick Coghlan <ncoghlan at gmail.com> wrote:
> On 7 October 2014 23:37, Barry Warsaw <barry at python.org> wrote:
>> On Oct 07, 2014, at 11:34 AM, Antoine Pitrou wrote:
>>
>>>IMO it's reasonable, but assuming we devise a dedicated protocol for
>>>getting a path's representation (e.g. __strpath__). Concrete type
>>>checking should be avoided.
>>
>> What would __strpath__ do that __str__ wouldn't do?  Or do you think it's
>> better to explicitly disallow str-like objects that aren't path objects?
>>
>> What I'm trying to understand is whether str(argument) is that "path protocol"
>> or whether there's a good reason that something else that's specifically not
>> str-ification is required.
>
> It's mostly a matter of offering better failure modes - the reasons
> would be similar to why we added operator.index and __index__ in order
> to expand various APIs from "only int or long objects" without
> expanding them so far that they also accepted float objects or strings
> the way coercing via "int" would.
>
> Using str(x) implicitly allows lots of nonsense that should throw an
> immediate TypeError to instead throw OSError later on (or, worse,
> perhaps even appear to work).

Combining this thought with Chris Angelico's reply, I actually wonder
if the index vs int analogy is even more applicable than I first
thought.

What if the protocol was __text__ with a new text() builtin (or at
least an operator.text() function), and it was advised to only be
implemented by types where they were, at least conceptually, truly
representable as strings?

That's basically what was done with the __index__ method in
http://www.python.org/dev/peps/pep-0357/ to introduce ducktyping to
several APIs that previously only worked with builtin int/long
objects.

Cheers,
Nick.

-- 
Nick Coghlan   |   ncoghlan at gmail.com   |   Brisbane, Australia


More information about the Python-ideas mailing list