In IPython, it is fairly easy to provide tab-completion for user-defined object: simply define a __dir__
method that returns a list of strings to the object.
IPython also provide us with a way to define our own custom magic functions using the handy register_line_magic
utility. In some ~/.ipython/profile_default/startup/magictest.py
:
from IPython.core.magic import register_line_magic
@register_line_magic
def show(dataType):
# do something depending on the given `dataType` value
Now my question is: how to provide auto-completion to this magic function?
According to this email, one should look into IPython.core.interactiveshell.InteractiveShell.init_completer()
for an example of magic function completers such as %reset
, '%cd', etc...
However, in the same startup file as the one in which my magic function is defined, the following code didn't work:
from IPython.core.interactiveshell import InteractiveShell
def show_complete():
return ['dbs', 'databases', 'collections']
InteractiveShell._instance.set_hook(
'complete_command', show_complete, str_key='%show')
In the IPython shell, typing %show TAB
triggers nothing (print statements in the function show that the function is not even called).
Could somebody point me out on some documentation or examples on how to define such user-magic command parameters completion from within the Ipython startup files?
Thanks!
You can use this:
def load_ipython_extension(ipython):
def apt_completers(self, event):
""" This should return a list of strings with possible completions.
Note that all the included strings that don't start with event.symbol
are removed, in order to not confuse readline.
"""
return ['update', 'upgrade', 'install', 'remove']
ipython.set_hook('complete_command', apt_completers, re_key = '%%apt')
%%apt is the magic keyword
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments