Skip to content

Making docs accessible to Python only and / or Rust only. #5269

@davidhewitt

Description

@davidhewitt

At the moment if we have a function like the following:

/// A function to add two numbers together.
///
/// # Examples
///
/// ```rust
/// let x = sum(10, 12);
/// assert_eq!(x, 22);
/// ```
/// 
/// ``` python
/// >>> assert sum(10, 12) == 22
/// ```
///
/// # Errors
/// 
/// This function panics on overflow of `i32`.
#[pyfunction]
fn sum(x: i32, y: i32) -> i32 { ... }

Then we currently copy the whole docstring from Rust to Python. This is not ideal; it would be nice to be able to have a Rust-specific example which is only visible from rustdoc and a Python-specific example which is only visible from Python.

I think we might be able to solve this by having a #[pyo3(doc)] attribute which we can use to switch mode for consuming docs into the final form for each language.

I think it might be something like:

  • #[pyo3(doc = "rust")] - docs from this point onward are left in-place for Rustdoc and stripped from Python docstring
  • #[pyo3(doc = "py")] - docs from this point onward are stripped from Rustdoc and included in the Python docstring. I think we can do this by manipulating the expanded #[doc] attributes, but needs confirmation.
  • #[pyo3(doc = "both")] - docs from this point onwards are visible in both languages. This is the default mode all docs start in.

So the above might be written something like:

/// A function to add two numbers together.
///
/// # Examples
///
#[pyo3(doc = "rust")] // rust-only example
/// ```rust
/// let x = sum(10, 12);
/// assert_eq!(x, 22);
/// ```
///
#[pyo3(doc = "py")]  // python-only example
/// ``` python
/// >>> assert sum(10, 12) == 22
/// ```
///
#[pyo3(doc = "both")]  // show the errors section in both languages
/// # Errors
/// 
/// This function panics on overflow of `i32`.
#[pyfunction]
fn sum(x: i32, y: i32) -> i32 { ... }

What do folks think?

There might be better forms like #[pyo3(doc(rust))] / #[pyo3(doc(py))] etc. If the concept is proven to work we can bikeshed the syntax.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions