Skip to content

Use Cython as numba alternative #266

@felixhekhorn

Description

@felixhekhorn

related to #185 - for the moment I use this issue to save my work on a different place than just my computer ... eventually, I think, I can turn this into an PR.

at the moment it seems doing just poetry build is not enough, but doing just before a cythonize -X language_level=3 -a -i myfile.pyx seems to be sufficient

cc @scarrazza

Resources

Files

`pyproject.toml`
[tool.poetry]
name = "pkgcy"
version = "0.0.0"
description = "Blubbes"
authors = ["Lorem Ipsum <lorem@ip.sum>"]
license = "MIT"
keywords = []

packages = [
    { include = "pkgcy" },
    # { include = "tests", format = "sdist" },
]
include = [
    # { path = "meson.build", format = "sdist" },
    # { path = "py.typed" },
    # C extensions must be included in the wheel distributions
    { path = "*.so", format = "wheel" },
    { path = "*.pyd", format = "wheel" }, # for Windows
]


[tool.poetry.dependencies]
python = "^3.8,<3.12"
numpy = "^1.24"
scipy = "^1.10.1"

[tool.poetry.group.dev.dependencies]
cython = ">=3.0.0b2"

[tool.poetry.build]
generate-setup-file = false
script = "mybuild.py" # the name build.py is taken by poetry itself


[build-system]
requires = ["poetry-core>=1.1.0a6", "Cython>=3.0.0b2"] # or >= 0.29?
build-backend = "poetry.core.masonry.api"
`pkgcy/__init__.py`
from scipy.integrate import quad
import os

if os.environ.get("BUILD_WHEEL",False):
    pass
else:
    import pyximport; pyximport.install()

from myfile import f as g

def f(x):
    return x

def run():
    return quad(g, 0.,1.)
`mybuild.py`
import os

# See if Cython is installed
try:
    from Cython.Build import cythonize
# Do nothing if Cython is not available
except ImportError:
    # Got to provide this function. Otherwise, poetry will fail
    def build(setup_kwargs):
        pass
# Cython is installed. Compile
else:
    # from setuptools import Extension
    # from setuptools.dist import Distribution
    from distutils.command.build_ext import build_ext

    # This function will be executed in setup.py:
    def build(setup_kwargs):
        # The file you want to compile
        extensions = [
            "myfile.pyx"
        ]

        # gcc arguments hack: enable optimizations
        os.environ['CFLAGS'] = '-O3'

        # Build
        setup_kwargs.update({
            'ext_modules': cythonize(
                extensions,
                language_level=3,
                compiler_directives={'linetrace': True},
            ),
            'cmdclass': {'build_ext': build_ext}
        })
`myfile.pyx`
# cython: language_level=3
def f(x):
    return x*x*x

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions