Using Cython 3.0 and Numpy in Python code

56 views
Skip to first unread message

Abbeville

unread,
Sep 7, 2024, 9:37:30 AM9/7/24
to cython-users
Hi. I have a moderate amount of experience with Cython 2.x and Numpy 1.x. Today, my Python 3.x code is fully typed and passes mypy successfully. My understanding of Cython 3.x is, this annotated Python code can be used in some way instead of the classic method. But, how?  All the Python and Numpy code is of the form:

import numpy as np
import numpy.typing as npt

def do_glory(a: npt.NDArray[np.uint32], r: int, t: int) -> npt.NDArray[np.float32]:
    b: npt.NDArray[np.float32] = np.sin((a * r), dtype=np.float32)
    c: npt.NDArray[np.float32] = np.cos((a * t), dtype=np.float32)
    return (b+c) / (r +t)

Thank-you :)

da-woods

unread,
Sep 8, 2024, 10:11:29 AM9/8/24
to cython...@googlegroups.com
Hi,

We don't make any use of numpy.typing type annotations.

Essentially there's two ways in Cython to use Numpy arrays efficiently:

1. ndarray (cimported from Numpy)
2. typed memoryviews

ndarray is the older way of doing it and has some limitations. It isn't possible to use it with annotations/pure Python code and we don't plan to add it.

typed memoryviews are the more modern way of doing it. These can be used with anything that has the buffer protocol (including Numpy arrays). These can be used in annotations as `cython.double[:]` for example. Unfortunately this syntax doesn't really match the strict format for typing that mypy demands so there's some conflict there.

Unfortunately I don't think there's a way to use mypy compatible typing syntax to express the details that Cython wants to know about an array (that it supports the buffer protocol, the underlying C data type, and the number of dimensions) so you're kind of stuck pleasing either mypy or Cython.
Thank-you :) --

---
You received this message because you are subscribed to the Google Groups "cython-users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to cython-users...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/cython-users/bf720893-ed27-49c9-aa47-824b430115e5n%40googlegroups.com.


Abbeville

unread,
Sep 8, 2024, 1:04:41 PM9/8/24
to cython-users
Ah, ok. Does this mean a .pyx file has to be created for code with typed memoryviews?
Reply all
Reply to author
Forward
0 new messages