Skip to content

Commit

Permalink
Optimization: only analyze traceback if needed
Browse files Browse the repository at this point in the history
  • Loading branch information
mrbean-bremen committed Oct 6, 2024
1 parent 956d7af commit c60987c
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 2 deletions.
1 change: 1 addition & 0 deletions pyfakefs/fake_open.py
Original file line number Diff line number Diff line change
Expand Up @@ -89,6 +89,7 @@ def fake_open(
if is_called_from_skipped_module(
skip_names=skip_names,
case_sensitive=filesystem.is_case_sensitive,
check_open_code=sys.version_info >= (3, 12),
):
return io_open( # pytype: disable=wrong-arg-count
file,
Expand Down
14 changes: 12 additions & 2 deletions pyfakefs/helpers.py
Original file line number Diff line number Diff line change
Expand Up @@ -478,12 +478,19 @@ def putvalue(self, value: bytes) -> None:
self._bytestream.write(value)


def is_called_from_skipped_module(skip_names: list, case_sensitive: bool) -> bool:
def is_called_from_skipped_module(
skip_names: list, case_sensitive: bool, check_open_code: bool = False
) -> bool:
def starts_with(path, string):
if case_sensitive:
return path.startswith(string)
return path.lower().startswith(string.lower())

# in most cases we don't have skip names and won't need the overhead
# of analyzing the traceback, except when checking for open_code
if not skip_names and not check_open_code:
return False

stack = traceback.extract_stack()

# handle the case that we try to call the original `open_code`
Expand All @@ -494,12 +501,15 @@ def starts_with(path, string):
# -3: fake_io.open: 'return fake_open('
# -4: fake_io.open_code : 'return self._io_module.open_code(path)'
if (
sys.version_info >= (3, 12)
check_open_code
and stack[-4].name == "open_code"
and stack[-4].line == "return self._io_module.open_code(path)"
):
return True

if not skip_names:
return False

caller_filename = next(
(
frame.filename
Expand Down

0 comments on commit c60987c

Please sign in to comment.