Skip to content

Commit 558865e

Browse files
committed
Rolled back suppression of KeyError
line_profiler/_line_profiler.pyx::LineProfiler.c_last_time No longer suppressing the `KeyError` when accessed on a thread without profiling data; now wrapping the `KeyError` with a more helpful message tests/test_line_profiler.py::test_last_time() Updated to reflect the above change
1 parent 0472943 commit 558865e

2 files changed

Lines changed: 25 additions & 7 deletions

File tree

line_profiler/_line_profiler.pyx

Lines changed: 11 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -346,10 +346,19 @@ cdef class LineProfiler:
346346

347347
@property
348348
def c_last_time(self):
349+
"""
350+
Raises:
351+
KeyError
352+
If no profiling data is available on the current thread.
353+
"""
349354
try:
350355
return (<dict>self._c_last_time)[threading.get_ident()]
351-
except KeyError: # We haven't actually profiled anything yet
352-
return {}
356+
except KeyError as e:
357+
# We haven't actually profiled anything yet
358+
raise (KeyError('No profiling data on the current thread '
359+
'(`threading.get_ident()` = '
360+
f'{threading.get_ident()})')
361+
.with_traceback(e.__traceback__)) from None
353362

354363
@property
355364
def code_map(self):

tests/test_line_profiler.py

Lines changed: 14 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -86,20 +86,29 @@ def test_last_time():
8686
are consistent.
8787
"""
8888
prof = LineProfiler()
89+
with pytest.raises(KeyError, match='[Nn]o profiling data'):
90+
prof.c_last_time
91+
92+
def get_last_time(prof, *, c=False):
93+
try:
94+
return getattr(prof, 'c_last_time' if c else 'last_time')
95+
except KeyError:
96+
return {}
8997

9098
@prof
9199
def func():
92-
return prof.c_last_time.copy(), prof.last_time.copy()
100+
return (get_last_time(prof, c=True).copy(),
101+
get_last_time(prof).copy())
93102

94103
# These are always empty outside a profiling context
95104
# (hence the need of the above function to capture the transient
96105
# values)
97-
assert not prof.c_last_time
98-
assert not prof.last_time
106+
assert not get_last_time(prof, c=True)
107+
assert not get_last_time(prof)
99108
# Inside `func()`, both should get an entry therefor
100109
clt, lt = func()
101-
assert not prof.c_last_time
102-
assert not prof.last_time
110+
assert not get_last_time(prof, c=True)
111+
assert not get_last_time(prof)
103112
assert set(clt) == {hash(func.__wrapped__.__code__.co_code)}
104113
assert set(lt) == {func.__wrapped__.__code__}
105114

0 commit comments

Comments
 (0)