[Python-ideas] Working with Path objects: p-strings?

Koos Zevenhoven k7hoven at gmail.com
Tue Mar 29 06:24:48 EDT 2016


On Tue, Mar 29, 2016 at 10:49 AM, Paul Moore <p.f.moore at gmail.com> wrote:

> On 29 March 2016 at 08:22, Sven R. Kunze <srkunze at mail.de> wrote:
> > Thinking more about it, that would even come in nicely with path
> separators:
> >
> > p'/{whereever}/{youwant}/{togo}'
> >
> > That'll finally an easy-to-write and readable path generation. Great
> idea,
> > Stephen.
>
> P(wherever)/youwant/togo
>
> is as good, if not better - just "from pathlib import Path as P" (or
> use Path(wherever) if you don't like unnecessary 1-letter aliases...)



Yes. I assume you meant  P('/') /wherever/youwant/togo. Or with p-strings,

    p'/' /wherever/youwant/togo

I'm not necessarily against Sven's version either, but my first thoughts
about the power of combined pf strings would be something like this
(assuming Sven's implicit f):

    all_data = [p'data{i}.txt'.read_text() for i in range(1, 307)]

which would read the contents of data1.txt, data2.txt, ..., and data306.txt
into a list.

And below, to the security issue raised by Sjoerd.


On Tue, Mar 29, 2016 at 10:46 AM, Sjoerd Job Postmus <sjoerdjob at sjec.nl>
wrote:

> On Tue, Mar 29, 2016 at 06:27:09PM +1100, Chris Angelico wrote:
> > On Tue, Mar 29, 2016 at 6:22 PM, Sven R. Kunze <srkunze at mail.de> wrote:
> > > Thinking more about it, that would even come in nicely with path
> separators:
> > >
> > > p'/{whereever}/{youwant}/{togo}'
> > >
> > > That'll finally an easy-to-write and readable path generation. Great
> idea,
> > > Stephen.
> >
> > Agreed, although this introduces a new edge case: what if 'togo'
> > contains a slash? Should this raise an exception, or should it be
> > interpreted as a multi-part path component? Arguments can be put for
> > both sides.
>
> As we all know, togo is user input containing
>     ../../../../../../../../../../../../../../../etc/passwd
>
>
How about

    p'/' /wherever/youwant//togo

That is, the floordiv operator could be used to prevent 'togo' from going
up the directory tree with "../../" or "/etc/passwd". The // would thus
restrict the user (who provides `togo`) into /wherever/youwant/ and it its
subdirectories.

-Koos
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20160329/d9def58e/attachment.html>


More information about the Python-ideas mailing list