Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add cached version of os.path.isfile to avoid repetitive I/O #2501

Merged
merged 4 commits into from
Aug 11, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 3 additions & 3 deletions astroid/interpreter/_import/spec.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@
from typing import Any, Literal, NamedTuple, Protocol

from astroid.const import PY310_PLUS
from astroid.modutils import EXT_LIB_DIRS
from astroid.modutils import EXT_LIB_DIRS, cached_os_path_isfile

from . import util

Expand Down Expand Up @@ -167,7 +167,7 @@ def find_module(
for suffix in suffixes:
package_file_name = "__init__" + suffix
file_path = os.path.join(package_directory, package_file_name)
if os.path.isfile(file_path):
if cached_os_path_isfile(file_path):
return ModuleSpec(
name=modname,
location=package_directory,
Expand All @@ -176,7 +176,7 @@ def find_module(
for suffix, type_ in ImportlibFinder._SUFFIXES:
file_name = modname + suffix
file_path = os.path.join(entry, file_name)
if os.path.isfile(file_path):
if cached_os_path_isfile(file_path):
return ModuleSpec(name=modname, location=file_path, type=type_)
return None

Expand Down
2 changes: 2 additions & 0 deletions astroid/manager.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@
NoSourceFile,
_cache_normalize_path_,
_has_init,
cached_os_path_isfile,
file_info_from_modpath,
get_source_file,
is_module_name_part_of_extension_package_whitelist,
Expand Down Expand Up @@ -471,6 +472,7 @@ def clear_cache(self) -> None:
LookupMixIn.lookup,
_cache_normalize_path_,
_has_init,
cached_os_path_isfile,
util.is_namespace,
ObjectModel.attributes,
ClassDef._metaclass_lookup_attribute,
Expand Down
6 changes: 6 additions & 0 deletions astroid/modutils.py
Original file line number Diff line number Diff line change
Expand Up @@ -604,6 +604,12 @@ def is_relative(modname: str, from_file: str) -> bool:
)


@lru_cache(maxsize=1024)
def cached_os_path_isfile(path: str | os.PathLike) -> bool:
"""A cached version of os.path.isfile that helps avoid repetitive I/O"""
return os.path.isfile(path)


# internal only functions #####################################################


Expand Down
Loading