##// END OF EJS Templates
first review pass on widget tests
first review pass on widget tests

File last commit:

r14753:9ab757fa
r14797:85a0de32
Show More
Variable Inspector.ipynb
569 lines | 16.4 KiB | text/plain | TextLexer
/ examples / widgets / Variable Inspector.ipynb

Variable Inspector Widget

A short example implementation.

This notebook demonstrates how one can use the widgets already built-in to IPython to create a working variable inspector much like the ones seen in popular commercial scientific computing environments.

In [17]:
class VariableInspectorWindow(object):
    
    # For this example file, the import sit inside the class, just to avoid poluting 
    # the namespace further.
    from IPython.html import widgets # Loads the Widget framework.
    from IPython.core.magics.namespace import NamespaceMagics # Used to query namespace.
    
    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 = self.NamespaceMagics()
        self.namespace.shell = ipython.kernel.shell
        
        self._popout = self.widgets.PopupWidget()
        self._popout.description = "Variable Inspector"
        self._popout.button_text = self._popout.description

        self._modal_body = self.widgets.ContainerWidget()
        self._modal_body.set_css('overflow-y', 'scroll')

        self._modal_body_label = self.widgets.HTMLWidget(value = 'Not hooked')
        self._modal_body.children = [self._modal_body_label]

        self._modal_footer = self.widgets.ContainerWidget()
        self._var_filter = self.widgets.ToggleButtonsWidget(description="Method:", values=['List', 'Details'], value='List')
        self._modal_footer.children = [self._var_filter]

        self._popout.children = [
            self._modal_body, 
            self._modal_footer,
        ]
        
        self._ipython = ipython
        self._ipython.register_post_execute(self._fill)
        self._var_filter.on_trait_change(self._fill, 'value')

    def close(self):
        """Close and remove hooks."""
        if not self.closed:
            del self._ipython._post_execute[self._fill]
            self._popout.close()
            self.closed = True
            VariableInspectorWindow.instance = None

    def _fill(self):
        """Fill self with variable information."""
        values = self.namespace.who_ls()
        mode = self._var_filter.value
        if mode == "List":
            self._modal_body_label.value = '<br>'.join(values)
        elif mode == "Details":
            self._modal_body_label.value = '<table class="table table-bordered table-striped"><tr><th>Name</th><th>Type</th><th>Value</th></tr><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>'

    def _ipython_display_(self):
        """Called when display() or pyout is used to display the Variable 
        Inspector."""
        self._popout._ipython_display_()
        self._modal_footer.add_class('modal-footer')
        self._popout.add_class('vbox')
        self._modal_body.add_class('box-flex1')
In [18]:
inspector = VariableInspectorWindow(get_ipython())
inspector

Test

In [11]:
a = 5
In [12]:
b = 3.0
In [13]:
c = a * b
In [14]:
d = "String"
In [15]:
del b
In [16]:
?
In [15]:
dir()
Out[15]:
['In',
 'Out',
 'VariableInspectorWindow',
 '_',
 '_10',
 '_14',
 '__',
 '___',
 '__builtin__',
 '__builtins__',
 '__doc__',
 '__name__',
 '__package__',
 '_dh',
 '_i',
 '_i1',
 '_i10',
 '_i11',
 '_i12',
 '_i13',
 '_i14',
 '_i15',
 '_i2',
 '_i3',
 '_i4',
 '_i5',
 '_i6',
 '_i7',
 '_i8',
 '_i9',
 '_ih',
 '_ii',
 '_iii',
 '_oh',
 '_sh',
 'exit',
 'get_ipython',
 'quit',
 'widgets']
In [4]:
dir(get_ipython().kernel.shell)
Out[4]:
['Completer',
 'CustomTB',
 'InteractiveTB',
 'SyntaxTB',
 '__class__',
 '__delattr__',
 '__dict__',
 '__doc__',
 '__format__',
 '__getattribute__',
 '__hash__',
 '__init__',
 '__module__',
 '__new__',
 '__reduce__',
 '__reduce_ex__',
 '__repr__',
 '__setattr__',
 '__sizeof__',
 '__str__',
 '__subclasshook__',
 '__weakref__',
 '_add_notifiers',
 '_call_pdb',
 '_config_changed',
 '_exit_now_changed',
 '_exiter_default',
 '_find_my_config',
 '_format_user_obj',
 '_get_call_pdb',
 '_get_exc_info',
 '_indent_current_str',
 '_inspect',
 '_instance',
 '_ipython_dir_changed',
 '_last_input_line',
 '_load_config',
 '_main_mod_cache',
 '_notify_trait',
 '_object_find',
 '_ofind',
 '_ofind_property',
 '_orig_sys_module_state',
 '_orig_sys_modules_main_mod',
 '_orig_sys_modules_main_name',
 '_post_execute',
 '_prompt_in1_changed',
 '_prompt_in2_changed',
 '_prompt_out_changed',
 '_prompt_pad_left_changed',
 '_prompt_trait_changed',
 '_remove_notifiers',
 '_reply_content',
 '_run_cached_cell_magic',
 '_set_call_pdb',
 '_showtraceback',
 '_trait_dyn_inits',
 '_trait_notifiers',
 '_trait_values',
 '_user_obj_error',
 '_walk_mro',
 'alias_manager',
 'all_ns_refs',
 'ask_exit',
 'ask_yes_no',
 'ast_node_interactivity',
 'ast_transformers',
 'atexit_operations',
 'auto_rewrite_input',
 'autocall',
 'autoindent',
 'automagic',
 'builtin_trap',
 'cache_size',
 'call_pdb',
 'class_config_section',
 'class_get_help',
 'class_get_trait_help',
 'class_print_help',
 'class_trait_names',
 'class_traits',
 'cleanup',
 'clear_instance',
 'clear_main_mod_cache',
 'color_info',
 'colors',
 'colors_force',
 'comm_manager',
 'compile',
 'complete',
 'config',
 'configurables',
 'custom_exceptions',
 'data_pub',
 'data_pub_class',
 'db',
 'debug',
 'debugger',
 'deep_reload',
 'default_user_namespaces',
 'define_macro',
 'define_magic',
 'del_var',
 'dir_stack',
 'disable_failing_post_execute',
 'display_formatter',
 'display_pub',
 'display_pub_class',
 'display_trap',
 'displayhook',
 'displayhook_class',
 'drop_by_id',
 'enable_gui',
 'enable_matplotlib',
 'enable_pylab',
 'ev',
 'ex',
 'excepthook',
 'execution_count',
 'exit_now',
 'exiter',
 'extension_manager',
 'extract_input_lines',
 'filename',
 'find_cell_magic',
 'find_line_magic',
 'find_magic',
 'find_user_code',
 'get_ipython',
 'get_parent',
 'getoutput',
 'has_readline',
 'history_length',
 'history_manager',
 'home_dir',
 'hooks',
 'indent_current_nsp',
 'init_alias',
 'init_builtins',
 'init_comms',
 'init_completer',
 'init_create_namespaces',
 'init_data_pub',
 'init_display_formatter',
 'init_display_pub',
 'init_displayhook',
 'init_encoding',
 'init_environment',
 'init_extension_manager',
 'init_history',
 'init_hooks',
 'init_inspector',
 'init_instance_attrs',
 'init_io',
 'init_ipython_dir',
 'init_latextool',
 'init_logger',
 'init_logstart',
 'init_magics',
 'init_payload',
 'init_pdb',
 'init_prefilter',
 'init_profile_dir',
 'init_prompts',
 'init_pushd_popd_magic',
 'init_readline',
 'init_syntax_highlighting',
 'init_sys_modules',
 'init_traceback_handlers',
 'init_user_ns',
 'init_virtualenv',
 'initialized',
 'input_splitter',
 'input_transformer_manager',
 'inspector',
 'instance',
 'ipython_dir',
 'keepkernel_on_exit',
 'kernel',
 'logappend',
 'logfile',
 'logger',
 'logstart',
 'magic',
 'magics_manager',
 'meta',
 'mktempfile',
 'more',
 'multiline_history',
 'new_main_mod',
 'ns_table',
 'object_info_string_level',
 'object_inspect',
 'on_trait_change',
 'parent',
 'parent_header',
 'payload_manager',
 'pdb',
 'pre_readline',
 'prefilter',
 'prefilter_manager',
 'prepare_user_module',
 'profile',
 'profile_dir',
 'prompt_in1',
 'prompt_in2',
 'prompt_manager',
 'prompt_out',
 'prompts_pad_left',
 'push',
 'pycolorize',
 'pylab_gui_select',
 'quiet',
 'raw_input_original',
 'readline',
 'readline_delims',
 'readline_no_record',
 'readline_parse_and_bind',
 'readline_remove_delims',
 'readline_use',
 'refill_readline_hist',
 'register_magic_function',
 'register_magics',
 'register_post_execute',
 'reset',
 'reset_selective',
 'restore_sys_module_state',
 'rl_do_indent',
 'rl_next_input',
 'run_ast_nodes',
 'run_cell',
 'run_cell_magic',
 'run_code',
 'run_line_magic',
 'runcode',
 'safe_execfile',
 'safe_execfile_ipy',
 'safe_run_module',
 'save_sys_module_state',
 'section_names',
 'separate_in',
 'separate_out',
 'separate_out2',
 'set_autoindent',
 'set_completer_frame',
 'set_custom_completer',
 'set_custom_exc',
 'set_hook',
 'set_next_input',
 'set_parent',
 'set_readline_completer',
 'show_rewritten_input',
 'show_usage',
 'show_usage_error',
 'showindentationerror',
 'showsyntaxerror',
 'showtraceback',
 'starting_dir',
 'stdin_encoding',
 'strdispatchers',
 'sys_excepthook',
 'system',
 'system_piped',
 'system_raw',
 'tempfiles',
 'trait_metadata',
 'trait_names',
 'traits',
 'transform_ast',
 'update_config',
 'user_expressions',
 'user_global_ns',
 'user_module',
 'user_ns',
 'user_ns_hidden',
 'user_variables',
 'var_expand',
 'wildcards_case_sensitive',
 'write',
 'write_err',
 'xmode']
In [ ]: