Skip to content

pyo3 and inspect.get_annotations #3054

Discussion options

You must be logged in to vote

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'>}

Replies: 3 comments 1 reply

Comment options

You must be logged in to vote
0 replies
Comment options

You must be logged in to vote
1 reply
@konstin
Comment options

Answer selected by dean-shaff
Comment options

You must be logged in to vote
0 replies
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
3 participants