PyCharm 2024.2 Help

Cython support

Prerequisites

PyCharm provides initial Cython support out of the box. PyCharm recognizes .pyx, .pxd, and .pxi files, and allows you to edit them. You can also compile these files into .so files using the Cython package.

Cython support

Cython files are marked with the cython icon.

Cython support includes:

Get started with Cython in PyCharm

Follow this procedure to create a .pyx file in PyCharm, edit it, and build it into a .so file using setup.py.

  1. Create a new project as explained in Create a Python project.

  2. Press Ctrl+Alt+S to open the project settings and navigate to Project: <project name> | Python Interpreter.

  3. Click Add a package on the package toolbar, then type Cython in the search field of the Available Packages dialog, and click Install Package. Close the window upon successful installation and click OK in the interpreter settings.

    Installing the Cython package
  4. Now create a .pyx file. Select File | New from the main menu, then select File. Type the filename, for example, example.pyx and save the changes. The file opens in the editor.

  5. You can copy and paste the following code:

    def function (a: int, b: int) -> str: return str(a + b) function(2, 4)

    Alternatively, you can type code to see how PyCharm assists you with code completion and type checking:

    cython code completion
    cython type checking
  6. Now create the setup.py file. Select Tools | Create setup.py from the main menu. PyCharm creates a template setup.py file and opens it in the editor. You can copy and paste the following setup options:

    from setuptools import setup, Extension module = Extension ('example', sources=['example.pyx']) setup( name='cythonTest', version='1.0', author='jetbrains', ext_modules=[module] )
  7. To compile the example.pyx file, select Tools | Run setup.py Task command from the main menu. In the Enter setup.py task name type build and select the build_ext task. For more information, refer to Create and run setup.py.

    selecting the build task

    In the Run Setup Task build_ext dialog, add the --inplace command-line agrument

    adding a command-line argument

    Once the build task successfully completes, the .so file is created.

    compilation with the build task

At this point, you can use the compiled .so file to import function:

from example import function

See Cython documentation for the complete instructions.

Last modified: 11 October 2024