python 18 lines · 6 steps

Filtering files with pathlib.glob

A generator streams matching source files while a helper collects config files across several patterns.

Explained by highlit
1from pathlib import Path
2from typing import Iterator
3 
4 
5def find_source_files(root: Path, pattern: str = "**/*.py") -> Iterator[Path]:
6 ignored = {".git", "__pycache__", ".venv", "node_modules"}
7 for path in sorted(root.glob(pattern)):
8 if any(part in ignored for part in path.parts):
9 continue
10 if path.is_file():
11 yield path
12 
13 
14def collect_configs(root: Path) -> list[Path]:
15 matches: list[Path] = []
16 for pattern in ("*.ini", "*.toml", "*.yaml", "*.yml", ".env*"):
17 matches.extend(root.glob(pattern))
18 return sorted(set(matches))
01 / 01
STEP 01

Walkthrough

Space play step click any line
Three takeaways
  1. 1Yielding paths lets callers process files lazily instead of building a full list in memory.
  2. 2Checking path.parts against an ignore set skips whole directory trees cheaply.
  3. 3Running multiple globs and deduplicating with a set gives clean, sorted results.

Related explainers

Share this explainer

Here's the card — post it anywhere.

Filtering files with pathlib.glob — share card
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code