Skip to content

bpo-29235: Make cProfile.Profile a context manager. #6808

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

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions Doc/library/profile.rst
Original file line number Diff line number Diff line change
Expand Up @@ -262,6 +262,16 @@ functions:
ps.print_stats()
print(s.getvalue())

The :class:`Profile` class can also be used as a context manager (see
:ref:`typecontextmanager`)::

import cProfile

with cProfile.Profile() as pr:
# ... do something ...

pr.print_stats()

.. method:: enable()

Start collecting profiling data.
Expand Down
7 changes: 7 additions & 0 deletions Lib/cProfile.py
Original file line number Diff line number Diff line change
Expand Up @@ -110,6 +110,13 @@ def runcall(self, func, *args, **kw):
finally:
self.disable()

def __enter__(self):
self.enable()
return self

def __exit__(self, *exc_info):
self.disable()

# ____________________________________________________________

def label(code):
Expand Down
27 changes: 27 additions & 0 deletions Lib/test/test_cprofile.py
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,33 @@ def test_module_path_option(self):
# Test successful run
assert_python_ok('-m', 'cProfile', '-m', 'timeit', '-n', '1')

def test_profile_enable_disable(self):
prof = self.profilerclass()
# Make sure we clean ourselves up if the test fails for some reason.
self.addCleanup(prof.disable)

prof.enable()
self.assertIs(sys.getprofile(), prof)

prof.disable()
self.assertIs(sys.getprofile(), None)

def test_profile_as_context_manager(self):
prof = self.profilerclass()
# Make sure we clean ourselves up if the test fails for some reason.
self.addCleanup(prof.disable)

with prof as __enter__return_value:
# profile.__enter__ should return itself.
self.assertIs(prof, __enter__return_value)

# profile should be set as the global profiler inside the
# with-block
self.assertIs(sys.getprofile(), prof)

# profile shouldn't be set once we leave the with-block.
self.assertIs(sys.getprofile(), None)


def test_main():
run_unittest(CProfileTest)
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
The :class:`cProfile.Profile` class can now be used as a context manager.
You can profile a block of code by running::

import cProfile
with cProfile.Profile() as profiler:
# ... code to be profiled ...

Patch by Scott Sanderson.