import IPython, ipykernel, inspect
self = ip = IPython.get_ipython()
old_object_inspect, old_object_inspect_text = ip.object_inspect, ip.object_inspect_text
The standard ipykernel
uses two methods from the shell to compose the return message for inspection. self.object_inspect
is used to determine if a inspection exists then self.object_inspect_text
returns the actual ipykernel.ipkernel.IPythonKernel.do_inspect
message body.
print(inspect.getsource(ipykernel.ipkernel.IPythonKernel.do_inspect))
def do_inspect(self, code, cursor_pos, detail_level=0): name = token_at_cursor(code, cursor_pos) info = self.shell.object_inspect(name) reply_content = {'status' : 'ok'} reply_content['data'] = data = {} reply_content['metadata'] = {} reply_content['found'] = info['found'] if info['found']: info_text = self.shell.object_inspect_text( name, detail_level=detail_level, ) data['text/plain'] = info_text return reply_content
object_inspect
must always return a found result and object_inspect_text
will return out custom inspection results.
def object_inspect(oname, detail_level=0):
return IPython.core.oinspect.object_info(found=True)
def object_inspect_text(oname, detail_level=0):
try: return old_object_inspect_text(oname, detail_level=0)
except KeyError: ...
return define(oname)
Replace running IPython inspectors with these new functions.
def load_ipython_extension(ip):
ip.object_inspect, ip.object_inspect_text = object_inspect, object_inspect_text
def unload_ipython_extension(ip):
global old_object_inspect, old_object_inspect_text
ip.object_inspect, ip.object_inspect_text = old_object_inspect, old_object_inspect_text
__name__ == '__main__' and load_ipython_extension(get_ipython())
The ip.inspector
in JupyterLab will show definitions for words
.
define
will fetch a word definition if it is in our word list.
def define(object):
if object in words: return object + '\n' + str(dictionary.meaning(object))
return ""
We use spacy
to define our set
of valid words. By knowing the valid words
we can minimize the number of requests made.
import spacy
words = set(x.text for x in spacy.load('en').vocab)
PyDictionary
makes requests
for the definitions. We can add requests_cache
to speak up repeated requests
.
from PyDictionary import PyDictionary
dictionary = PyDictionary()
import requests_cache, requests
requests_cache.install_cache('dictionary')