Why exception from os.path.exists()?

Marko Rauhamaa marko at pacujo.net
Thu Jun 7 05:29:27 EDT 2018


Antoon Pardon <antoon.pardon at vub.be>:

> On 07-06-18 05:55, Steven D'Aprano wrote:
>> As a Python programmer, how does treating NUL specially make our life
>> better?
>
> By treating possible path values differently from impossible path
> values.

There are all kinds of impossibility. The os.stat() reports those
impossibilities via an OSError exception. It's just that
os.path.exists() converts the OSError exception into a False return
value. A ValueError is raised by the Python os.stat() wrapper to
indicate that it can't even deliver the request to the kernel.

The application programmer doesn't give an iota who determined the
impossibility of a pathname. Unfortunately, os.path.exists() forces the
distinction on the application. If I have to be prepared to catch a
ValueError from os.path.exists(), what added value does os.path.exists()
give on top of os.stat()? The whole point of os.path.exists() is

  1. To provide an operating-system-independent abstraction.

  2. To provide a boolean interface instead of an exception interface.



This is a security risk. Here is a brief demonstration. Copy the example
HTTP server from:

   <URL: https://docs.python.org/3/library/http.server.html?highlight=h
   ttp#http.server.SimpleHTTPRequestHandler>

Run the server. Try these URLs in your browser:

  1. http://localhost:8000/

     => The directory listing is provided

  2. http://localhost:8000/test.html

     => A file is served or an HTTP error response (404) is generated

  3. http://localhost:8000/te%00st.html

     => The server crashes with a ValueError and the TCP connection is
        reset


Marko



More information about the Python-list mailing list