Skip to content

Commit

Permalink
Use inspect to determine when we leave the utils module
Browse files Browse the repository at this point in the history
Previously using the filename the code could be confused if
there was another lsst/utils directory in the path. Now
using inspect.getmodule the code can no for sure when it
leaves the lsst.utils module.
  • Loading branch information
timj committed Oct 15, 2021
1 parent 25fdfb9 commit 3d2cd24
Showing 1 changed file with 10 additions and 4 deletions.
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"):
# 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

0 comments on commit 3d2cd24

Please sign in to comment.