Coverage for /pythoncovmergedfiles/medio/medio/usr/local/lib/python3.8/site-packages/IPython/core/display_trap.py: 42%
26 statements
« prev ^ index » next coverage.py v7.4.4, created at 2024-04-20 06:09 +0000
« prev ^ index » next coverage.py v7.4.4, created at 2024-04-20 06:09 +0000
1# encoding: utf-8
2"""
3A context manager for handling sys.displayhook.
5Authors:
7* Robert Kern
8* Brian Granger
9"""
11#-----------------------------------------------------------------------------
12# Copyright (C) 2008-2011 The IPython Development Team
13#
14# Distributed under the terms of the BSD License. The full license is in
15# the file COPYING, distributed as part of this software.
16#-----------------------------------------------------------------------------
18#-----------------------------------------------------------------------------
19# Imports
20#-----------------------------------------------------------------------------
22import sys
24from traitlets.config.configurable import Configurable
25from traitlets import Any
27#-----------------------------------------------------------------------------
28# Classes and functions
29#-----------------------------------------------------------------------------
32class DisplayTrap(Configurable):
33 """Object to manage sys.displayhook.
35 This came from IPython.core.kernel.display_hook, but is simplified
36 (no callbacks or formatters) until more of the core is refactored.
37 """
39 hook = Any()
41 def __init__(self, hook=None):
42 super(DisplayTrap, self).__init__(hook=hook, config=None)
43 self.old_hook = None
44 # We define this to track if a single BuiltinTrap is nested.
45 # Only turn off the trap when the outermost call to __exit__ is made.
46 self._nested_level = 0
48 def __enter__(self):
49 if self._nested_level == 0:
50 self.set()
51 self._nested_level += 1
52 return self
54 def __exit__(self, type, value, traceback):
55 if self._nested_level == 1:
56 self.unset()
57 self._nested_level -= 1
58 # Returning False will cause exceptions to propagate
59 return False
61 def set(self):
62 """Set the hook."""
63 if sys.displayhook is not self.hook:
64 self.old_hook = sys.displayhook
65 sys.displayhook = self.hook
67 def unset(self):
68 """Unset the hook."""
69 sys.displayhook = self.old_hook