Created
May 24, 2012 06:50
-
-
Save ellisonbg/2779875 to your computer and use it in GitHub Desktop.
Cython Magic using pyximport
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{ | |
"metadata": { | |
"name": "cython_magic" | |
}, | |
"nbformat": 3, | |
"worksheets": [ | |
{ | |
"cells": [ | |
{ | |
"cell_type": "code", | |
"collapsed": true, | |
"input": [ | |
"from IPython.core.magic import register_line_cell_magic" | |
], | |
"language": "python", | |
"outputs": [], | |
"prompt_number": 4 | |
}, | |
{ | |
"cell_type": "code", | |
"collapsed": true, | |
"input": [ | |
"@register_line_cell_magic", | |
"def cython(line, cell):", | |
" \"\"\"Compile and import a cell as a .pyx file.\"\"\"", | |
" import sys", | |
" from importlib import import_module", | |
" module = line.strip()", | |
" fname = module + '.pyx'", | |
" with open(fname,'w') as f:", | |
" f.write(cell)", | |
" if 'pyximport' not in sys.modules:", | |
" import pyximport", | |
" pyximport.install(reload_support=True)", | |
" globals()[module] = import_module(module)" | |
], | |
"language": "python", | |
"outputs": [], | |
"prompt_number": 11 | |
}, | |
{ | |
"cell_type": "code", | |
"collapsed": false, | |
"input": [ | |
"%%cython bam", | |
"def f(x):", | |
" return 2.0*x" | |
], | |
"language": "python", | |
"outputs": [], | |
"prompt_number": 11 | |
}, | |
{ | |
"cell_type": "code", | |
"collapsed": false, | |
"input": [ | |
"reload(bam)" | |
], | |
"language": "python", | |
"outputs": [ | |
{ | |
"output_type": "pyout", | |
"prompt_number": 12, | |
"text": [ | |
"<module 'bam' from '/Users/bgranger/.pyxbld/lib.macosx-10.5-x86_64-2.7/bam.so.reload3'>" | |
] | |
} | |
], | |
"prompt_number": 12 | |
}, | |
{ | |
"cell_type": "code", | |
"collapsed": false, | |
"input": [ | |
"bam.f(10)" | |
], | |
"language": "python", | |
"outputs": [ | |
{ | |
"output_type": "pyout", | |
"prompt_number": 13, | |
"text": [ | |
"20.0" | |
] | |
} | |
], | |
"prompt_number": 13 | |
}, | |
{ | |
"cell_type": "code", | |
"collapsed": true, | |
"input": [ | |
"" | |
], | |
"language": "python", | |
"outputs": [] | |
} | |
] | |
} | |
] | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment