Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Error on extracting numpy boolean #3637

Closed
124C41p opened this issue Dec 10, 2023 · 0 comments · Fixed by #3638
Closed

Error on extracting numpy boolean #3637

124C41p opened this issue Dec 10, 2023 · 0 comments · Fixed by #3638

Comments

@124C41p
Copy link

124C41p commented Dec 10, 2023

In most circumstances numpy scalar types can be used as drop in replacements to Python's scalar types. PyO3 is almost no exception to this rule as it can successfully extract Rust types from many numpy types such as np.int32, np.float32, etc. However, for some reason it is not possible to extract a Rust boolean from a numpy boolean. Consider this example:

// lib.rs
use pyo3::prelude::*;

#[pyfunction]
fn bool_as_string(a: bool) -> PyResult<String> {
    Ok(a.to_string())
}

#[pyfunction]
fn int_as_string(a: i32) -> PyResult<String> {
    Ok(a.to_string())
}
#[pymodule]
fn my_module(_py: Python, m: &PyModule) -> PyResult<()> {
    m.add_function(wrap_pyfunction!(bool_as_string, m)?)?;
    m.add_function(wrap_pyfunction!(int_as_string, m)?)?;
    Ok(())
}
# test.py
import numpy as np
from my_module import bool_as_string, int_as_string

a = np.int32(42)
print(int_as_string(a))
print(bool_as_string(a > 0))

When running python test.py, the first print statement prints 42 as expected. The second print statement however raises an exception:

Traceback (most recent call last):
  File "/home/****/****/test.py", line 6, in <module>
    print(bool_as_string(a > 0))
TypeError: argument 'a': 'bool_' object cannot be converted to 'PyBool'

There is a simple workaround, as the numpy boolean can be easily converted to a Python boolean before calling the Rust function.

print(bool_as_string(bool(a > 0))) # works

However, it would still be nice if this issue could be fixed within PyO3 as it is hard to differentiate between Python booleans and numpy booleans as a developer in a project which heavily relies on numpy.

This was tested with the latest versions of PyO3 (0.20.0) and numpy (1.26.2).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
1 participant