变量检查器部件#

一个简单的示例实现#

这个笔记本演示了如何使用小部件为 IPython 内核创建一个工作的变量检查器,就像在流行的商业科学计算环境中看到的那样。

import ipywidgets as widgets # Loads the Widget framework.
from IPython.core.magics.namespace import NamespaceMagics # Used to query namespace.

# For this example, hide these names, just to avoid polluting the namespace further
get_ipython().user_ns_hidden['widgets'] = widgets
get_ipython().user_ns_hidden['NamespaceMagics'] = NamespaceMagics
class VariableInspectorWindow(object):
    instance = None
    
    def __init__(self, ipython):
        """Public constructor."""
        if VariableInspectorWindow.instance is not None:
            raise Exception("""Only one instance of the Variable Inspector can exist at a 
                time.  Call close() on the active instance before creating a new instance.
                If you have lost the handle to the active instance, you can re-obtain it
                via `VariableInspectorWindow.instance`.""")
        
        VariableInspectorWindow.instance = self
        self.closed = False
        self.namespace = NamespaceMagics()
        self.namespace.shell = ipython.kernel.shell
        
        self._box = widgets.Box()
        self._box.layout.overflow = 'visible scroll'
        self._table = widgets.HTML(value = 'Not hooked')
        self._box.children = [self._table]
        
        self._ipython = ipython
        self._ipython.events.register('post_run_cell', self._fill)
        
    def close(self):
        """Close and remove hooks."""
        if not self.closed:
            self._ipython.events.unregister('post_run_cell', self._fill)
            self._box.close()
            self.closed = True
            VariableInspectorWindow.instance = None

    def _fill(self):
        """Fill self with variable information."""
        values = self.namespace.who_ls()
        self._table.value = '<div class="rendered_html jp-RenderedHTMLCommon"><table><thead><tr><th>Name</th><th>Type</th><th>Value</th></tr></thead><tr><td>' + \
            '</td></tr><tr><td>'.join(['{0}</td><td>{1}</td><td>{2}'.format(v, type(eval(v)).__name__, str(eval(v))) for v in values]) + \
            '</td></tr></table></div>'

    def _repr_mimebundle_(self, **kwargs):
        return self._box._repr_mimebundle_(**kwargs)
inspector = VariableInspectorWindow(get_ipython())
inspector
Error in callback <bound method VariableInspectorWindow._fill of <__main__.VariableInspectorWindow object at 0x7f6f20e25af0>> (for post_run_cell), with arguments args (<ExecutionResult object at 7f6f20d3ba10, execution_count=4 error_before_exec=None error_in_exec=None info=<ExecutionInfo object at 7f6f20d3ba70, raw_cell="inspector = VariableInspectorWindow(get_ipython()).." store_history=True silent=False shell_futures=True cell_id=None> result=<__main__.VariableInspectorWindow object at 0x7f6f20e25af0>>,),kwargs {}:
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
TypeError: VariableInspectorWindow._fill() takes 1 positional argument but 2 were given

Test#

a = 5
Error in callback <bound method VariableInspectorWindow._fill of <__main__.VariableInspectorWindow object at 0x7f6f20e25af0>> (for post_run_cell), with arguments args (<ExecutionResult object at 7f6f20eee060, execution_count=5 error_before_exec=None error_in_exec=None info=<ExecutionInfo object at 7f6f20d61d00, raw_cell="a = 5" store_history=True silent=False shell_futures=True cell_id=None> result=None>,),kwargs {}:
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
TypeError: VariableInspectorWindow._fill() takes 1 positional argument but 2 were given
b = 3.0
Error in callback <bound method VariableInspectorWindow._fill of <__main__.VariableInspectorWindow object at 0x7f6f20e25af0>> (for post_run_cell), with arguments args (<ExecutionResult object at 7f6f20d63bf0, execution_count=6 error_before_exec=None error_in_exec=None info=<ExecutionInfo object at 7f6f20d63bc0, raw_cell="b = 3.0" store_history=True silent=False shell_futures=True cell_id=None> result=None>,),kwargs {}:
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
TypeError: VariableInspectorWindow._fill() takes 1 positional argument but 2 were given
c = a * b
Error in callback <bound method VariableInspectorWindow._fill of <__main__.VariableInspectorWindow object at 0x7f6f20e25af0>> (for post_run_cell), with arguments args (<ExecutionResult object at 7f6f20e26060, execution_count=7 error_before_exec=None error_in_exec=None info=<ExecutionInfo object at 7f6f20d62030, raw_cell="c = a * b" store_history=True silent=False shell_futures=True cell_id=None> result=None>,),kwargs {}:
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
TypeError: VariableInspectorWindow._fill() takes 1 positional argument but 2 were given
d = "String"
Error in callback <bound method VariableInspectorWindow._fill of <__main__.VariableInspectorWindow object at 0x7f6f20e25af0>> (for post_run_cell), with arguments args (<ExecutionResult object at 7f6f20dc0dd0, execution_count=8 error_before_exec=None error_in_exec=None info=<ExecutionInfo object at 7f6f20dc0d40, raw_cell="d = "String"" store_history=True silent=False shell_futures=True cell_id=None> result=None>,),kwargs {}:
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
TypeError: VariableInspectorWindow._fill() takes 1 positional argument but 2 were given
del b
Error in callback <bound method VariableInspectorWindow._fill of <__main__.VariableInspectorWindow object at 0x7f6f20e25af0>> (for post_run_cell), with arguments args (<ExecutionResult object at 7f6f20dc1e50, execution_count=9 error_before_exec=None error_in_exec=None info=<ExecutionInfo object at 7f6f20dc1e80, raw_cell="del b" store_history=True silent=False shell_futures=True cell_id=None> result=None>,),kwargs {}:
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
TypeError: VariableInspectorWindow._fill() takes 1 positional argument but 2 were given
inspector.close()