Skip to content

Instantly share code, notes, and snippets.

@ellisonbg
Created May 24, 2012 06:50
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 ellisonbg/2779875 to your computer and use it in GitHub Desktop.
Save ellisonbg/2779875 to your computer and use it in GitHub Desktop.
Cython Magic using pyximport
Display the source blob
Display the rendered blob
Raw
{
"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