PyO3 / PyO3/pyo3

implicit conversions

Open
#2,482 5 comments 1 reaction 0 assignees View on GitHub

Nobody has claimed this yet.

Dominant language
Rust
Stars
16.2k
Forks
1k
Avg merge
2d 6h
Merged PRs (30d)
66

Description

Thanks for the great work you do on PyO3.

Pybind11 has a feature called 'implicit conversions'
https://pybind11.readthedocs.io/en/stable/advanced/classes.html#implicit-conversions

This can be quite handy, let me give an example:

#[pyclass]
#[derive(Clone, Copy)]
pub struct Vector3D {
    pub x: f64
    pub y: f64
    pub z: f64
}

#[pymethods]
impl Vector3D {
    #new
    pub fn __new__(v: [f64, 3]) -> Self {
        Self {x: v[0], y: v[1], z: v[2]}
    }
}


#[pyfunction]
fn do_something(vec: Vector3D) -> f64 {
    vec.x * 2
}
>>> from py_rust_module import *

>>> do_something([1,2,3])
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: argument 'vec': 'list' object cannot be converted to 'Vector3D'

>>> do_something(Vector3D([1,2,3]))
2

In Pybind11 Vector3D could be declared as implicitly convertible from list and do_something([1,2,3]) would be valid and implicitly casting the list to a Vector3D object.

Is this something that could be done in pyo3? It is quite handy and can save a lot of verbosity...

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start by reviewing PyO3's existing argument-conversion behavior and the linked Pybind11 implicit-conversions documentation. The issue's target behavior is that a Python list can be passed directly to a function expecting a Vector3D; completion should include an agreed design and coverage for that conversion.

Written by the indexing model from the issue text.

Assessment

Tech stack
python, rust
Domain
api
Issue type
Feature
Difficulty
5/5
Estimated time
Over a week
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
32/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.