I have a function which compares a file path against two lists of folder paths. It returns true if the start of the path matches any folder from list A (include
) but doesn't match an optional list B (exclude
).
from typing import List, Optional
def match(file: str, include: List[str], exclude: Optional[List[str]]=None):
return any(file.startswith(p) for p in include) and not any(
file.startswith(p) for p in exclude
)
The function works as expected if all parameter values are provided, but fails with a TypeError if no exclude
folders are given.
# True
match(file="source/main.py", include=["source/", "output/"], exclude=["output/debug/"])
# False
match(file="output/debug/output.log", include=["source/", "output/"], exclude=["output/debug/"])
# Expected result - True
# Actual result - TypeError: 'NoneType' object is not iterable
match(file="output/debug/output.log", include=["source/", "output/"])
There was a PEP proposal to introduce null-aware operators that may have helped, but it has not been implemented as of now.
How can I safely iterate over an Optional list in Python without running into null errors?