Skip to content

Instantly share code, notes, and snippets.

@knowsuchagency
Last active January 22, 2024 12:19
Show Gist options
  • Save knowsuchagency/f7b2203dd613756a45f816d6809f01a6 to your computer and use it in GitHub Desktop.
Save knowsuchagency/f7b2203dd613756a45f816d6809f01a6 to your computer and use it in GitHub Desktop.
A cell magic to enable the use of mypy within jupyter notebooks
"""
Add mypy type-checking cell magic 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.
The line magic is called "typecheck" to avoid namespace conflict with the mypy
package.
"""
from IPython.core.magic import register_cell_magic
@register_cell_magic
def typecheck(line, cell):
"""
Run the following cell though mypy.
Any parameters that would normally be passed to the mypy cli
can be passed on the first line, with the exception of the
-c flag we use to pass the code from the cell we want to execute
i.e.
%%typecheck --ignore-missing-imports
...
...
...
mypy stdout and stderr will print prior to output of cell. If there are no conflicts,
nothing will be printed by mypy.
"""
from IPython import get_ipython
from mypy import api
# inserting a newline at the beginning of the cell
# ensures mypy's output matches the the line
# numbers in jupyter
cell = '\n' + cell
mypy_result = api.run(['-c', cell] + line.split())
if mypy_result[0]: # print mypy stdout
print(mypy_result[0])
if mypy_result[1]: # print mypy stderr
print(mypy_result[1])
shell = get_ipython()
shell.run_cell(cell)
@BradyHu
Copy link

BradyHu commented Aug 14, 2019

Inspired by you, I wrote a similar one. https://gist.github.com/BradyHu/f4dc997d4b53f9b23e1120940fb8f0d1, thanks for your explorer work.

@XZF0
Copy link

XZF0 commented Aug 28, 2019

... nice! But it should ideally be also evaluating other cells with the magic, otherwise all relevant code must be in the same cell.

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