Search code examples
pythoncython

Is it possible to include .pyx in a file.py


I had a function in python which was 3 for loops to do some calculations. It was very slow so I looked for solutions to speed up my Python code and I saw Cython was a way to accelerate Python code. I wrote my Cython function in a notebook and it was working great so I wanted to include it to my existing project but now I can not import this function in other file to be called. I tried to do this method:

import pyximport
pyximport.install()
from my module import function_a, function_b

but it still gives me the following error : ModuleNotFoundError: No module named 'my_module'

I'm running Python 3.8.3 and Cython 0.29.21

My folder structure is the following

Folder

  • my_module.pyx
  • where_I_want_to_call.py

Solution

  • File structure:

    PS C:\Users\adeee\Desktop\test> tree /F
    C:.
        ip.pyx
        test.py
    

    So you can see that I have my main test.py file which I run. I also have an ip.pyx file from which I import check_ip function.

    Maybe you have some kind of typo in your code. I can see that you have

    from my module import function_a, function_b

    but you should have:

    from my_module import function_a, function_b

    It is important to include the _ sign.

    Code:

    test.py

    import pyximport
    pyximport.install()
    import ip
    
    if __name__ == '__main__':
        ip.check_ip('192.168.1.1')
    

    ip.pyx

    import ipaddress
    
    def check_ip(user_ip):
        try:
            ip = ipaddress.ip_address(user_ip)
            print(f'{ip} is correct. Version: IPv{ip.version}')
        except ValueError:
            print('Adress is invalid')
    

    Output:

    Generating code
    Finished generating code
    192.168.1.1 is correct. Version: IPv4
    

    Final:

    You have to import pyximport module and run pyximport.install() method before importing any *.pyx module. After running these two commands, you should have an imported module, just like a regular *.py file.