0

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?

Aran-Fey
  • 39,665
  • 11
  • 104
  • 149
  • The exceptions are raised by `os` module (like `os.scandir("invalid/path")`), while glob returns an empy generator – crissal Jun 30 '19 at 08:59
  • It might surprise you, but what you call invalid can actually be a valid path on UNIX operating systems. – Klaus D. Jun 30 '19 at 09:19

1 Answers1

2

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]: 

Adam.Er8
  • 12,675
  • 3
  • 26
  • 38
  • 1
    This simple experiment confirms the behavior of globbing a nonexistent path on one specific OS. How do I know the results will be the same if the path is invalid, or if I use a different OS? I'd rather not do experiments - I'm really looking for an official source that tells us what will happen. – Aran-Fey Jul 01 '19 at 12:47