Skip to content

Instantly share code, notes, and snippets.

@H2CO3
Last active January 5, 2019 20:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save H2CO3/59f81c1753022cc68c6572e7b60dacc2 to your computer and use it in GitHub Desktop.
Save H2CO3/59f81c1753022cc68c6572e7b60dacc2 to your computer and use it in GitHub Desktop.
'''
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 through 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.
'''
import IPython
import mypy.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 = mypy.api.run([
'--strict', '--strict-optional',
'--warn-redundant-casts', '--warn-no-return',
'--ignore-missing-imports',
] + line.split() + [
'-c', cell,
])
if mypy_result[0]: # print mypy stdout
print(mypy_result[0])
if mypy_result[1]: # print mypy stderr
print(mypy_result[1])
shell = IPython.get_ipython()
shell.run_cell(cell)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment