Skip to content

Commit 5e8fac7

Browse files
authored
Add cached version of os.path.isfile to avoid repetitive I/O (pylint-dev#2501)
1 parent 3a743a4 commit 5e8fac7

File tree

3 files changed

+11
-3
lines changed

3 files changed

+11
-3
lines changed

astroid/interpreter/_import/spec.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,7 @@
2121
from typing import Any, Literal, NamedTuple, Protocol
2222

2323
from astroid.const import PY310_PLUS
24-
from astroid.modutils import EXT_LIB_DIRS
24+
from astroid.modutils import EXT_LIB_DIRS, cached_os_path_isfile
2525

2626
from . import util
2727

@@ -167,7 +167,7 @@ def find_module(
167167
for suffix in suffixes:
168168
package_file_name = "__init__" + suffix
169169
file_path = os.path.join(package_directory, package_file_name)
170-
if os.path.isfile(file_path):
170+
if cached_os_path_isfile(file_path):
171171
return ModuleSpec(
172172
name=modname,
173173
location=package_directory,
@@ -176,7 +176,7 @@ def find_module(
176176
for suffix, type_ in ImportlibFinder._SUFFIXES:
177177
file_name = modname + suffix
178178
file_path = os.path.join(entry, file_name)
179-
if os.path.isfile(file_path):
179+
if cached_os_path_isfile(file_path):
180180
return ModuleSpec(name=modname, location=file_path, type=type_)
181181
return None
182182

astroid/manager.py

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,7 @@
2424
NoSourceFile,
2525
_cache_normalize_path_,
2626
_has_init,
27+
cached_os_path_isfile,
2728
file_info_from_modpath,
2829
get_source_file,
2930
is_module_name_part_of_extension_package_whitelist,
@@ -471,6 +472,7 @@ def clear_cache(self) -> None:
471472
LookupMixIn.lookup,
472473
_cache_normalize_path_,
473474
_has_init,
475+
cached_os_path_isfile,
474476
util.is_namespace,
475477
ObjectModel.attributes,
476478
ClassDef._metaclass_lookup_attribute,

astroid/modutils.py

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -604,6 +604,12 @@ def is_relative(modname: str, from_file: str) -> bool:
604604
)
605605

606606

607+
@lru_cache(maxsize=1024)
608+
def cached_os_path_isfile(path: str | os.PathLike) -> bool:
609+
"""A cached version of os.path.isfile that helps avoid repetitive I/O"""
610+
return os.path.isfile(path)
611+
612+
607613
# internal only functions #####################################################
608614

609615

0 commit comments

Comments
 (0)