Pybind11 dtype caster does not accept strings or type objects
Nobody has claimed this yet.
- Dominant language
- C++
- Stars
- 18k
- Forks
- 2.3k
- Avg merge
- 5d 17h
- Merged PRs (30d)
- 10
Description
Issue description
If you bind a function where one of the arguments is a pybind11::dtype, the function does not automatically cast str objects or type objects to dtype. In contrast, all Numpy functions accept str or type arguments for their dtype: e.g. np.zeros(10, dtype=float) or np.zeros(10, dtype="float32") are both valid.
Reproducible example code
When I write:
#include <pybind11/pybind11.h>
#include <pybind11/numpy.h>
PYBIND11_MODULE(mymodule, m) {
m.def("test_dtype_cast", [](pybind11::dtype t) {
pybind11::print(t);
});
}
and call:
import numpy as np
import mymodule as m
m.test_dtype_cast("float32")
I get the error:
TypeError: test_dtype_cast(): incompatible function arguments. The following argument types are supported:
1. (arg0: dtype) -> None
Invoked with: 'float32'
Similarly, when I call
import numpy as np
import mymodule as m
m.test_dtype_cast(np.float32)
I get an error:
TypeError: test_dtype_cast(): incompatible function arguments. The following argument types are supported:
1. (arg0: dtype) -> None
Invoked with: <class 'numpy.float32'>
Both these cases should get implicitly casted to pybind11::dtype.
Contributor guide
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
Research direction
Start with the reproducible PYBIND11_MODULE example and inspect how pybind11::dtype arguments are converted. Compare the shown string and numpy.float32 calls with NumPy's accepted dtype inputs; done means both forms are accepted when passed to test_dtype_cast, with coverage for the reported cases.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- cpp, numpy, python
- Domain
- api
- Issue type
- Bug
- Difficulty
- 3/5
- Estimated time
- 1-2 days
- Activity status
- Stale
- Clarity
- Mostly clear
- Newbie friendliness
- 45/100