| 1 |
# encoding: utf-8 |
| 2 |
""" |
| 3 |
A context manager for handling sys.displayhook. |
| 4 |
|
| 5 |
Authors: |
| 6 |
|
| 7 |
* Robert Kern |
| 8 |
* Brian Granger |
| 9 |
""" |
| 10 |
|
| 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 |
#----------------------------------------------------------------------------- |
| 17 |
|
| 18 |
#----------------------------------------------------------------------------- |
| 19 |
# Imports |
| 20 |
#----------------------------------------------------------------------------- |
| 21 |
|
| 22 |
import sys |
| 23 |
|
| 24 |
from traitlets.config.configurable import Configurable |
| 25 |
from traitlets import Any |
| 26 |
|
| 27 |
#----------------------------------------------------------------------------- |
| 28 |
# Classes and functions |
| 29 |
#----------------------------------------------------------------------------- |
| 30 |
|
| 31 |
|
| 32 |
class DisplayTrap(Configurable): |
| 33 |
"""Object to manage sys.displayhook. |
| 34 |
|
| 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 |
""" |
| 38 |
|
| 39 |
hook = Any() |
| 40 |
|
| 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 |
| 47 |
|
| 48 |
def __enter__(self): |
| 49 |
if self._nested_level == 0: |
| 50 |
self.set() |
| 51 |
self._nested_level += 1 |
| 52 |
return self |
| 53 |
|
| 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 |
| 60 |
|
| 61 |
@property |
| 62 |
def is_active(self) -> bool: |
| 63 |
return self._nested_level != 0 |
| 64 |
|
| 65 |
def set(self): |
| 66 |
"""Set the hook.""" |
| 67 |
if sys.displayhook is not self.hook: |
| 68 |
self.old_hook = sys.displayhook |
| 69 |
sys.displayhook = self.hook |
| 70 |
|
| 71 |
def unset(self): |
| 72 |
"""Unset the hook.""" |
| 73 |
sys.displayhook = self.old_hook |
| 74 |
|