Aran-Fey
Aran-Fey

Reputation: 43276

How does pathlib's glob() handle nonexistent and invalid paths?

Say I have a path to a nonexistent directory:

dirpath = Path("this/directory/doesnt/exist")

or even a completely invalid path:

dirpath = Path(r"D:\:$`~[]*/'/..")

If I call dirpath.glob('whatever'), one of two things can happen:

  1. It can throw an exception (FileNotFoundError/OSError)
  2. It can yield 0 results

The documentation, of course, doesn't contain any information about this. So, how does Path.glob() handle nonexistent and invalid paths?

Upvotes: 1

Views: 1685

Answers (1)

Adam.Er8
Adam.Er8

Reputation: 13413

It will yield 0 results, and I think the docs match this behavior by saying:

Glob the given relative pattern in the directory represented by this path, yielding all matching files (of any kind)

it's alright for "all" to also be 0.

just like the builtin all treats an empty iterable:

In [1]: all([])
Out[1]: True

a simple experiment can confirm:

In [1]: from pathlib import Path

In [2]: dirpath = Path("this/directory/doesnt/exist")

In [3]: glob_result = dirpath.glob("*")

In [4]: type(glob_result)
Out[4]: generator

In [5]: list(glob_result)
Out[5]: []

In [6]: 

Upvotes: 2

Related Questions