1"""
2A context manager for handling sys.displayhook.
3
4Authors:
5
6* Robert Kern
7* Brian Granger
8"""
9
10#-----------------------------------------------------------------------------
11# Copyright (C) 2008-2011 The IPython Development Team
12#
13# Distributed under the terms of the BSD License. The full license is in
14# the file COPYING, distributed as part of this software.
15#-----------------------------------------------------------------------------
16
17#-----------------------------------------------------------------------------
18# Imports
19#-----------------------------------------------------------------------------
20
21import sys
22
23from traitlets.config.configurable import Configurable
24from traitlets import Any
25
26#-----------------------------------------------------------------------------
27# Classes and functions
28#-----------------------------------------------------------------------------
29
30
31class DisplayTrap(Configurable):
32 """Object to manage sys.displayhook.
33
34 This came from IPython.core.kernel.display_hook, but is simplified
35 (no callbacks or formatters) until more of the core is refactored.
36 """
37
38 hook = Any()
39
40 def __init__(self, hook=None):
41 super().__init__(hook=hook, config=None)
42 self.old_hook = None
43 # We define this to track if a single DisplayTrap is nested.
44 # Only turn off the trap when the outermost call to __exit__ is made.
45 self._nested_level = 0
46
47 def __enter__(self):
48 if self._nested_level == 0:
49 self.set()
50 self._nested_level += 1
51 return self
52
53 def __exit__(self, type, value, traceback):
54 if self._nested_level == 1:
55 self.unset()
56 self._nested_level -= 1
57 # Returning False will cause exceptions to propagate
58 return False
59
60 @property
61 def is_active(self) -> bool:
62 return self._nested_level != 0
63
64 def set(self):
65 """Set the hook."""
66 if sys.displayhook is not self.hook:
67 self.old_hook = sys.displayhook
68 sys.displayhook = self.hook
69
70 def unset(self):
71 """Unset the hook."""
72 sys.displayhook = self.old_hook