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

DM-32210: Use inspect to determine when we leave the utils module #103

Merged
merged 1 commit into from
Oct 16, 2021
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
14 changes: 10 additions & 4 deletions python/lsst/utils/timer.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@
import resource
import time
import datetime
import traceback
import inspect
from contextlib import contextmanager

from typing import (
Expand Down Expand Up @@ -94,14 +94,20 @@ def _find_outside_stacklevel() -> int:
keyword parameter ``stacklevel``.
"""
stacklevel = 1 # the default for `Logger.log`
stack = traceback.extract_stack()
for i, s in enumerate(reversed(stack)):
if "lsst/utils" not in s.filename:
for i, s in enumerate(inspect.stack()):
module = inspect.getmodule(s.frame)
if module is None:
# Stack frames sometimes hang around so explicilty delete.
del s
continue
if not module.__name__.startswith("lsst.utils"):
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

With inspect and frames you need to be very careful about creating local references to frames, as you can create reference cycles, so the fewer local variables you need the better, and cleaning up variables that contain frames before exiting a function is a good idea. This may be overly defensive for how often this function gets used, but it is good practice, especially if someone uses it as a code reference later on.

Suggested change
if not module.__name__.startswith("lsst.utils"):
for i, s in enumerate(inspect.stack()):
module = inspect.getmodule(s.frame)
if module is None:
continue
if not module.__name__.statswith("lsst.utils"):
stacklevel = i
break
del s
return stacklevel

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This seems highly unpythonic but I'll make the change.

# 0 will be this function.
# 1 will be the caller which will be the default for `Logger.log`
# and so does not need adjustment.
stacklevel = i
break
# Stack frames sometimes hang around so explicilty delete.
del s

return stacklevel

Expand Down