Why exception from os.path.exists()?

Chris Angelico rosuav at gmail.com
Fri Jun 1 09:58:58 EDT 2018


On Fri, Jun 1, 2018 at 11:41 PM, Richard Damon <Richard at damon-family.org> wrote:
> 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. Thus we have
> several options.
>
> 1) we can treat os.path.exists('foo\0bar') the same as
> os.path.exists(1.5) and raise the exception.

1.5 raises TypeError, which is correct. But the type of "foo\0bar" is
str, which is a perfectly valid type. ValueError is more correct here.
And that's what currently happens.

Possibly more confusing, though, is this:

>>> os.path.exists(1)
True
>>> os.path.exists(2)
True
>>> os.path.exists(3)
False

I think it's testing that the file descriptors exist, because
os.path.exists is defined in terms of os.stat, which can stat a path
or an FD. So os.path.exists(fd) is True if that fd is open, and False
if it isn't. But os.path.exists is not documented as accepting FDs.
Accident of implementation or undocumented feature? Or maybe
accidental feature?

> 2) we can treat os.path.exists('foo\0bar') as specifying a file that can
> never exists and bypass the system call are return false.

That's what's being proposed.

> 3) we can process os.path.exists('foo\0bar') by just passing the string
> to the system call, making it the same as os.path.exists('foo')
>
> The last is probably the one that we can say is likely wrong, but
> arguments could be made for either of the first two.

More than "likely wrong"; it's definitely wrong, and deceptively so. I
don't think anyone would support this case.

ChrisA



More information about the Python-list mailing list