Hi,
I have created a Nim cell magic for Jupyter and JLab Notebooks (similar to e.g. %%cython, but for your favorite language :-P ). It is based on @yglukhov 's great nimpy library and I thought it could be useful to some of you.
With it, you can do the following in a Jupyter Notebook:
# In [1]
%load_ext nim_magic
# In [2]
%%nim mytest -d:release
proc greet(name: string): string {.exportpy.} =
return "Hello, " & name & "!"
# In [3]
mytest.greet("World")
# Out[3]
'Hello, World!'
It is just a single file, I put it in a gist. Place the file somewhere in Python's import path to use it.
Best, Axel
Cool, good to know. Good hint for the verbosity, I have added that. I deliberately did not use tcc, because I imagine when you want to build a compiled extension for Python, you want the fully optimized code. But of course, everybody is free to add that option.
In the meantime, I have made several changes after using it a bit more myself. Especially, I noticed that reloading of the same module after recompilation does not work, even when using importlib.reload() or other tricks. This is a reported Python bug.
To circumvent this, all symbols from the compiled modules are now imported into the current namespace, so that the above example now looks like this:
# In [1]:
%load_ext nim_magic
# In [2] (notice: no module name given anymore):
%%nim -d:release
proc greet(name: string): string {.exportpy.} =
return "Hello, " & name & "!"
# In [3]:
greet("World")
# Out [3]:
'Hello, World!'
# In [4] (this will remove temporary dirs created by nim_magic):
%nim_clear
This way, re-import works. Please have a look at the file documentation in the latest revision of the above linked gist for more details.
Best, Axel
Simple, but it looks very useful!!
Thank you for making this. The next time I'll be writing some Python code in the Notebooks, I'll give it a try to speed-up critical functions.