Skip to content

[Feature Request] add support for type annotation hints in #[text_signature] macro. #1112

@robinmoussu

Description

@robinmoussu

Would it be possible to extend the text_signature macro to be able to support python type annotation.

Example

/// Formats the sum of two numbers as string.
#[pyfunction()]
#[text_signature = "(a: int, b: int) -> str"]  //  <-- this line
fn sum_as_string(a: usize, b: usize) -> PyResult<String> {
    Ok((a+b).to_string())
}

Expected documentation:

sum_as_string(a: int, b: int) -> str
        Formats the sum of two numbers as string.

  • All arguments should be able to have a type annotation
  • The return type of the function could be added with ->type
  • According to the PEP any expression should be valid, but I think that limiting it only to types (and maybe quoted string) should be enough
  • I think that the types should be python types (python's int instead of rust's i64 for example)
  • Types used in the annotations don't need to be checked in the macro
    • In the example, I used int for the annotation of a and b even if Rust expect an usize since python doesn't have unsized integers
    • In the example, the return type of the function is just str and not PyResult

Note

After reading #310 (comment) I think that it's not possible to use the same machinery than type annotation in python code (which, from what I understand, would allow IDE to give better auto-completion hints). While waiting for the cpython bug to be fixed, it should still be possible that the text returned by help(sum_as_string) contains the type annotation even if __annotations__ isn't populated correctly (yet).

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions