0

There are a number of questions on SO about reloading Cython files in IPython (I'm using Spyder). Here's my implementation that appears to check all the boxes from other questions:

from importlib import reload
import pyximport
import sys
pyximport.install(reload_support=True)

try:
    del sys.modules['cython_test.ctest']
    del ctest
except:
    pass

import cython_test.ctest as ctest
ctest = reload(ctest)

ctest.test()

However, it doesn't work and I have to restart the kernel to get an updated version of the file.

In case it's relevant, here's how I'm generating the .so file:

from setuptools import setup
from Cython.Build import cythonize
import os

file = os.environ.get("CYTHONIZE_FILE", "")
setup(ext_modules=cythonize(f"{file}.pyx"))

And I would call this in the command line:

CYTHONIZE_FILE=ctest python setup.py build_ext --inplace

Any ideas?

SuperCodeBrah
  • 2,874
  • 2
  • 19
  • 33
  • 1
    After reload you need to once again import. For an explanation see https://stackoverflow.com/a/55172547/5769463 – ead Sep 28 '21 at 04:49
  • That explanation hinted at what the problem was. See my answer. So the `.so` file is needed only for running in the command line? Any explanation as to why one way works in IPython and the other way works in the terminal? – SuperCodeBrah Sep 28 '21 at 05:07
  • 1
    if you generate so-file by yourself, you should not use pyximport (it generates extensions in cache, i.e. our of place) as its purpose to build extensions on the fly. – ead Sep 28 '21 at 05:12

1 Answers1

1

The issue is apparently with building the file and creating the .so file. If I don't do this at all (i.e., completely remove the .so file and restart the kernel), the code I have works.

SuperCodeBrah
  • 2,874
  • 2
  • 19
  • 33