Skip to content

Commit cb7ecda

Browse files
committed
Add count_ctxmgr
1 parent 79abbb6 commit cb7ecda

1 file changed

Lines changed: 11 additions & 8 deletions

File tree

memory_profiler/line_profiler.py

Lines changed: 11 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
import pdb
22
import sys
33
import warnings
4+
from contextlib import contextmanager
45
from functools import wraps
56

67
from .code_map import CodeMap
@@ -48,27 +49,29 @@ def add_function(self, func):
4849
else:
4950
self.code_map.add(code)
5051

52+
@contextmanager
53+
def count_ctxmgr(self):
54+
self.enable_by_count()
55+
try:
56+
yield
57+
finally:
58+
self.disable_by_count()
59+
5160
def wrap_function(self, func):
5261
""" Wrap a function to profile it.
5362
"""
5463

5564
def f(*args, **kwds):
56-
self.enable_by_count()
57-
try:
65+
with self.count_ctxmgr():
5866
return func(*args, **kwds)
59-
finally:
60-
self.disable_by_count()
6167

6268
return f
6369

6470
def runctx(self, cmd, globals, locals):
6571
""" Profile a single executable statement in the given namespaces.
6672
"""
67-
self.enable_by_count()
68-
try:
73+
with self.count_ctxmgr():
6974
exec(cmd, globals, locals)
70-
finally:
71-
self.disable_by_count()
7275
return self
7376

7477
def enable_by_count(self):

0 commit comments

Comments
 (0)