Why exception from os.path.exists()?

Steven D'Aprano steve+comp.lang.python at pearwood.info
Fri Jun 1 18:10:38 EDT 2018


On Fri, 01 Jun 2018 09:41:04 -0400, Richard Damon wrote:

> I think this is a key point. os.path.exists needs to pass a null
> terminated string to the system to ask it about the file.

That's an implementation detail utterly irrelevant to Python programmers. 
If the OS expects a pointer to a block of UTF-16 bytes, would you say "oh 
well, since Python doesn't have low level pointers, we simply can't 
provide this functionality?"

No of course we would not. os.path.exists should take a regular Python 
string and adapt it to whatever the implementation requires.


> The question
> comes what should we do if we pass it a value that can't (or we won't)
> represent as such a string.

You get a TypeError:


py> os.path.exists([])
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/local/lib/python3.5/genericpath.py", line 19, in exists
    os.stat(path)
TypeError: argument should be string, bytes or integer, not list



> The confusion is that in python, a string with an embedded null is
> something pretty much like a string without an embedded null, so the
> programmer might not think of it as being the wrong type.

But it *isn't* the wrong type. It is the same type:


py> type("abc") is type("a\0c")
True


So TypeError is out, since the type is right, only the value is wrong. 
But ValueError is wrong too:

What does os.path.exists return when given "the wrong value" (i.e. a 
string that doesn't match an existing path)? It returns False, not raise 
an exception.


> Thus we have several options.

Only one of which is consistent with the rest of os.path.exist()'s 
behaviour, only one of which is sensible. Return False, like every other 
pathname that doesn't exist.




-- 
Steven D'Aprano
"Ever since I learned about confirmation bias, I've been seeing
it everywhere." -- Jon Ronson




More information about the Python-list mailing list