According to the fnmatch source code, the only special characters it recognizes are *
, ?
, [
and ]
. Hence any pattern that does not contain any of these will only match itself. We can therefore implement the cheapglob
mentioned in the question as
def cheapglob(s): return glob.glob(s) if re.search("[][*?]", s) else [s]
This will only hit the file system for patterns which include special characters. This differs subtly from a plain glob.glob
: For a pattern with no special characters like "foo.txt", this function will return ["foo.txt"]
regardless of whether that file exists, while glob.glob
will return []
if the file isn't there. So the calling function will need to handle the possibility that some of the returned files might not exist.