# using `typer` in ipython magics- [x] wrap function to consume system arguments using `typer`- [x] register the magic with `IPython`- [x] examples
- [x] ipython extensions
## wrapping the function
we needs to process system arguments as a string when use magics.
the line in a line magic or the first line in a cell magic may take arguments.
`wrap_magic` transforms our function into a magic style method that has the following signature.
def magicish(line: str, cell: str =None): ...
it uses `click` by way of `typer` to deserialize the line of system arguments.
these parameters are passed to the original function.
the magic function's help/docstring is replaced with the help from the command line interface.
8
wrap_magic
transforms our function into a magic style method that has the following signature.
def magicish(line: str, cell: str =None): ...
it uses
click
by way of
typer
to deserialize the line of system arguments.
these parameters are passed to the original function.
the magic function's help/docstring is replaced with the help from the command line interface.
defregister_magic(function,name=None,cell_key="cell"):importinspectfromIPythonimportget_ipythonshell=get_ipython()cache_rich_console()signature=inspect.signature(function)wrapper=wrap_magic(function,cell_key=cell_key)kind="line"ifcell_keyinsignature.parameters:kind="line_cell"ifsignature.parameters[cell_key].defaultisinspect._empty:kind="cell"shell.register_magic_function(wrapper,kind,name)shell.log.info(F"registered {repr(function)} as magic named {nameorfunction.__name__}")returnfunction
in our interactive condition we want access to the `rich` console that `typer` uses.
we're going to wrap a cache around `typer`s method so that each we recieve the same `rich.console.Console`
each time the function is invoked.
3
in our interactive condition we want access to the
rich
console that
typer
uses.
we're going to wrap a cache around
typer
s method so that each we recieve the same
rich.console.Console
each time the function is invoked.
if(Ø:="__file__"notinlocals()):importtyper@register_magicdefhello(count:int=5,name:str=typer.Option("world",help="a name to repeat"),msg:str="<3"):"""a function that says hello"""print(name*count,msg)assert"hello"notin(shell:=get_ipython()).magics_manager.magics["cell"]%hello
ifØ:@register_magicdefyall(count:int=5,name:str=typer.Option("world",help="a name to repeat"),cell:str="xoxo"):"""a function that says hello to yall"""hello(count,name,msg=cell)assert"yall"inshell.magics_manager.magics["cell"],"the method didn't get registered."