Rather than passing the widget variable into the magic each time we call it, it might be convenient to register the widget with the magic and persist it.
Inspired by Claude.ai, maybe something along the lines of:
from IPython.core.magic import Magics, magics_class, line_magic, cell_magic
from IPython.core.magic_arguments import (
argument, magic_arguments, parse_argstring
)
@magics_class
class MyAnywidgetMagic(Magics):
def __init__(self, shell):
super(MyAnywidgetMagic, self).__init__(shell)
self.widget_name = None # Store the widget variable name as an instance attribute
self.widget = None
def _set_widget(self, w_name=''):
w_name = w_name.strip()
if w_name:
self.widget_name = w_name
self.widget = self.shell.user_ns[self.widget_name]
# Perhaps add a test that it is a widget type, else None?
print(f"myAnyWidget object set to: {self.obj_name}")
@line_magic
def set_myAnywidget_object(self, line):
"""Set the object name to be used in subsequent myAnywidget_magic calls."""
self._set_widget(line)
@cell_magic
@magic_arguments()
@argument('-w', '--widget-name', type=string, help='widget variable name')
def myAnywidget_magic(self, line, cell):
"""Use the stored object name if no line argument is provided."""
args = parse_argstring(self.myAnywidget_magic, line)
if args.widget_name:
self. _set_widget(args.widget_name):
if self.widget is None :
print("Error: No widget / widget name set. Use %set_myAnywidget_object first to set the name.")
return
elif cell:
# Get the actual widget
w = self.widget
w.set_code_content(cell)
Rather than passing the widget variable into the magic each time we call it, it might be convenient to register the widget with the magic and persist it.
Inspired by Claude.ai, maybe something along the lines of: