Skip to main content

Lib/glob.py

cpython 3.14 @ ab2d84fe1023/Lib/glob.py

Lib/glob.py implements Unix-style filename pattern matching. glob() returns a sorted list; iglob() is a generator. The ** pattern recursively matches zero or more directory levels.

Map

LinesSymbolRole
1-80glob, iglobPublic entry points
81-200_iglob, _iterdir, _rlistdirInner generators: flat and recursive
201-280_glob_translateConvert glob pattern to re pattern
281-340fnmatch helpershas_magic, _ishidden utilities

Reading

** recursive matching

When a pattern segment is **, _rlistdir walks the directory tree using os.scandir and yields all nested paths. The ** pattern only matches whole directory components, not partial names.

# CPython: Lib/glob.py:143 _rlistdir
def _rlistdir(dirname, dironly):
names = _listdir(dirname, dironly)
for x in names:
yield x
path = os.path.join(dirname, x) if dirname else x
for y in _rlistdir(path, dironly):
yield os.path.join(x, y)

_glob_translate

_glob_translate(pat) converts a glob pattern to a re pattern:

  • * becomes [^/]* (any chars except /)
  • ** becomes .* (any chars including /)
  • ? becomes [^/]
  • [abc] becomes [abc] (character class)
  • [!abc] becomes [^abc]

Hidden files

On POSIX, * does not match dotfiles by default. glob and iglob have a hidden parameter (Python 3.13+) to explicitly include or exclude hidden files.

gopy notes

module/fnmatch/ provides fnmatch and fnmatchcase. glob requires os.scandir and os.listdir from module/os/. Planned path: module/glob/.