pyo3 and inspect.get_annotations #3054
-
I would like to be able to get type information about my Rust structs at runtime. #[pyclass]
#[pyo3(text_signature = "(start, end)")]
pub struct Foo {
#[pyo3(get)]
pub start: i64,
#[pyo3(get)]
pub end: i64,
} in Python land: >>> import inspect
>>> from my_module import Foo
>>> inspect.get_annotations(Foo)
{} Ideally, I would like to see something like >>> inspect.get_annotations(Foo)
{"start": <class 'int'>, "end": <class 'int'>} Looking at the |
Beta Was this translation helpful? Give feedback.
Replies: 3 comments 1 reply
-
This looks like the same problem as #510. To summarize, python unfortunately simply doesn't allow you to set |
Beta Was this translation helpful? Give feedback.
-
I implemented a work around for this. #[pyclass]
#[pyo3(text_signature = "(start, end)")]
pub struct Foo {
#[pyo3(get)]
pub start: i64,
#[pyo3(get)]
pub end: i64,
}
#[pymethods]
impl Foo {
#[classattr]
pub fn __annotations__(py: Python<'_>) -> PyResult<Py<PyAny>>
{
let builtins = PyModule::import(py, "builtins")?;
let t = builtins.getattr(intern!(py, "int"))?;
let dict = PyDict::new(py);
dict.set_item("start", t)?;
dict.set_item("end", t)?;
Ok(dict.into())
}
} Now in Python land >>> import inspect
>>> from my_module import Foo
>>> inspect.get_annotations(Foo)
{"start": <class 'int'>, "end": <class 'int'>} |
Beta Was this translation helpful? Give feedback.
-
Interesting. Automatically generating this class attr would be an OK approach if we can't find any alternative. |
Beta Was this translation helpful? Give feedback.
I implemented a work around for this.
Now in Python land