[Python-ideas] PEP 428 - object-oriented filesystem paths

Georg Brandl g.brandl at gmx.net
Sat Oct 6 19:57:02 CEST 2012


Am 06.10.2012 16:49, schrieb Stephen J. Turnbull:
> Antoine Pitrou writes:
> 
>  > >  > Someone else proposed overloading '+', which would be confusing
>  > >  > since we need to be able to combine paths and regular strings, for
>  > >  > ease of use.
>  > > 
>  > > Is it really that obnoxious to write "p + Path('bar')" (where p is a
>  > > Path)?
>  > > 
>  > > What about the case "'bar' + p"?  Since Python isn't C, you can't
>  > > express that as "'bar'[p]"!
>  > 
>  > The issue I envision is if you write `p + "bar"`, thinking p is a Path,
>  > and p is actually a str object. It won't raise, but give you the wrong
>  > result.
> 
> No, my point is that for me prepending new segments is quite common,
> though not as common as appending them.  The asymmetry of the bracket
> operator means that there's no easy way to deal with that.
> 
> On the other hand, `p + Path('foo')` and `Path('foo') + p` (where p is
> a Path, not a string) both seem reasonable to me.  It's true that one
> could screw up as you suggest, but that requires *two* mistakes, first
> thinking that p is a Path when it's a string, and then forgetting to
> convert 'bar' to Path.  I don't think that's very likely if you don't
> allow mixing strings and Paths without explicit conversion.

But having to call Path() explicitly every time is not very convenient either;
in that case you can also call .join() -- and I bet people would prefer

  p + Path('foo/bar/baz')

(which is probably not correct in all cases) to

  p + Path('foo') + Path('bar') + Path('baz')

just because it's such a pain.

On the other hand, when the explicit conversion is not needed, confusion
will ensue, as Antoine says.

In any case, for me using "+" to join paths is quite ugly.  I guess it's
because after all, I think of the underlying path as a string, and "+" is
hardwired in my brain as string concatenation (at least in Python).

Georg




More information about the Python-ideas mailing list