What is pyximport and how should I use it?

30,450

Solution 1

pyximport is part of Cython, and it's used in place of import in a way.

If your module doesn’t require any extra C libraries or a special build setup, then you can use the pyximport module to load .pyx files directly on import, without having to write a setup.py file. It can be used like this:

>>> import pyximport; pyximport.install()
>>> import helloworld
Hello World

Straight from the Cython documentation

Solution 2

You can use pyximport to automatically recompile and reload your .pyx module.

Remove what setup.py has generated, else you might load that extension module. pyximport does not use setup.py.

Let's assume a hello.pyx with a function mean2.

Start IPython.

In [1]: import pyximport
In [2]: pyximport.install(reload_support=True)
In [3]: from importlib import reload
In [4]: import hello
In [5]: hello.mean2(2,3)

The result:

Out [5]: 2.5

Leave that window and go to your editor to change hello.pyx.

Then go back to IPython and type

In [6]: reload(hello);import hello;hello.mean2(2,3)

You will see some text informing about the recompilation. Then the new result:

Out[6]: 'Mean of 2 and 3 is 2.5'
Share:
30,450

Related videos on Youtube

guilhermecgs
Author by

guilhermecgs

Updated on June 05, 2021

Comments

  • guilhermecgs
    guilhermecgs almost 3 years

    I am using cython to generate faster code for a mathematical model. I am having a hard time compiling the code, but somehow I managed to do so using a .bat:

    setlocal EnableDelayedExpansion
    
    CALL "C:\Program Files\Microsoft SDKs\Windows\v7.0\Bin\SetEnv.cmd" /x64 /release
    set DISTUTILS_USE_SDK=1
    
    C:\Python27\python.exe C:\gcsilve\trunk\myproject\myproject\cythonsetup.py build_ext --inplace
    
    PAUSE
    

    It runs ok...

    My question is regarding pyximport. I have old code written by someone else that uses pyximport.install(). I couldn't figure out what it does and why I should use it, since I am already compiling the code by myself. So, can someone explain to me in a very simple (for dummies) way what pyximport does?

    Additional information: I have a project1, using cython. I have a project2, that references project1.

  • guilhermecgs
    guilhermecgs about 11 years
    1) Considering that I already have compiled the code using a setup.py, i do not need to use pyximport, right?
  • Adam Barthelson
    Adam Barthelson about 11 years
    Yup, that's right. Was that what you were looking for? You can always accept if my answer so :), otherwise let me know.
  • Ryan
    Ryan about 6 years
    Im trying to install pyximport,but cannot find anything ,How did you install it?Thanks
  • user2682863
    user2682863 almost 6 years
    @Ryan it's included with Cython