Skip to content

Instantly share code, notes, and snippets.

@BradyHu
Created August 14, 2019 06:56
Show Gist options
  • Save BradyHu/f4dc997d4b53f9b23e1120940fb8f0d1 to your computer and use it in GitHub Desktop.
Save BradyHu/f4dc997d4b53f9b23e1120940fb8f0d1 to your computer and use it in GitHub Desktop.
An IPython notebook satrtup script to enable the use of mypy within jupyter notebooks
#! /usr/bin python3
# -*- coding:utf-8 -*-
"""
Add mypy type-checking ability to jupyter/ipython.
Save this script to your ipython profile's startup directory.
IPython's directories can be found via `ipython locate [profile]` to find the current ipython directory and ipython profile directory, respectively.
For example, this file could exist on a path like this on mac:
/Users/yourusername/.ipython/profile_default/startup/typecheck.py
where /Users/yourusername/.ipython/profile_default/ is the ipython directory for the default profile.
and the jupyter/ipython shell will do typecheck automatically.
"""
import re
from IPython import get_ipython
mypy_cells = ''
mypy_shell = get_ipython()
mypy_tmp_func = mypy_shell.run_cell
mypy_typecheck=True
def mypy_tmp(cell,*args,**kwargs):
if mypy_typecheck:
from mypy import api
global mypy_cells
mypy_cells_length = len(mypy_cells.split('\n'))-1
mypy_cells+=(cell+'\n')
mypy_result = api.run(['-c', mypy_cells])
if mypy_result[0]:
for line in mypy_result[0].strip().split('\n'):
l,n,r = re.compile('(<[a-z]+>:)(\d+)(.*?)$').findall(line)[0]
if int(n)>mypy_cells_length:
n = str(int(n)-mypy_cells_length)
print("".join([l,n,r]))
if mypy_result[1]:
print(mypy_result[1])
return mypy_tmp_func(cell,*args,**kwargs)
mypy_shell.run_cell = mypy_tmp
@sakehl
Copy link

sakehl commented May 12, 2020

I'm working on a facility based on this, to have some interactive use. It is internal for now, but I'll share it when I can.

Thanks for the initial gist btw!

@sakehl
Copy link

sakehl commented Mar 8, 2021

We've made it into an iPython extension, which can be found here: https://pypi.org/project/nb-mypy/

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment