Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit 58f5680

Browse files
committed
Issue #18810: Be optimistic with stat calls when seeing if a directory
exists when checking for a package. Before there was an isdir check and then various isfile checks for possible __init__ files when looking for a package. This change drops the isdir check by leaning on the assumption that a directory will not contain something named after the module being imported which is not a directory. If the module is a package then it saves a stat call. If there is nothing in the directory with the potential package name it also saves a stat call. Only if there is something in the directory named the same thing as the potential package will the number of stat calls increase (due to more wasteful __init__ checks). Semantically there is no change as the isdir check moved down so that namespace packages continue to have no chance of accidentally collecting non-existent directories.
1 parent 2546a17 commit 58f5680

2 files changed

Lines changed: 777 additions & 779 deletions

File tree

Lib/importlib/_bootstrap.py

Lines changed: 9 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1406,16 +1406,15 @@ def find_loader(self, fullname):
14061406
# Check if the module is the name of a directory (and thus a package).
14071407
if cache_module in cache:
14081408
base_path = _path_join(self.path, tail_module)
1409-
if _path_isdir(base_path):
1410-
for suffix, loader in self._loaders:
1411-
init_filename = '__init__' + suffix
1412-
full_path = _path_join(base_path, init_filename)
1413-
if _path_isfile(full_path):
1414-
return (loader(fullname, full_path), [base_path])
1415-
else:
1416-
# A namespace package, return the path if we don't also
1417-
# find a module in the next section.
1418-
is_namespace = True
1409+
for suffix, loader in self._loaders:
1410+
init_filename = '__init__' + suffix
1411+
full_path = _path_join(base_path, init_filename)
1412+
if _path_isfile(full_path):
1413+
return (loader(fullname, full_path), [base_path])
1414+
else:
1415+
# If a namespace package, return the path if we don't
1416+
# find a module in the next section.
1417+
is_namespace = _path_isdir(base_path)
14191418
# Check for a file w/ a proper suffix exists.
14201419
for suffix, loader in self._loaders:
14211420
full_path = _path_join(self.path, tail_module + suffix)

0 commit comments

Comments
 (0)