0

I'm trying to inline Python code in Rust, but it fails when the Python code has the operator for floor division // which is ignored as if it were a Rust comment.

For instance:

#![feature(proc_macro_hygiene)]
use inline_python::python;

fn main() {
    python! {
        print("Hi from PyO3")
        foo = 37.46 // 3
        print(foo)
    }
}

This will print 37.46 even though it should print 12.0 (the result of floor division of 37.46 by 3).

A possible solution is to replace this division by foo = math.floor(37.43 / 3), but I would prefer not to have to modify the Python code if possible. I'm also afraid it might impact performance.

Is there a way to use the floor division operator (or equivalent) in Python code embedded in Rust code with PyO3?

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
Clonk
  • 2,025
  • 1
  • 11
  • 26
  • 1
    The `//` operator desugars to `47.46.__floordiv__ (3)` so at least you can be sure that this won't affect performance. It still requires modifying your Python code though… – Jmb Dec 17 '19 at 15:31

1 Answers1

2

From the documentation:

The // and //= operators are unusable, as they start a comment.

Workaround: you can write ## instead, which is automatically converted to //.

So try

#![feature(proc_macro_hygiene)]
use inline_python::python;

fn main() {
    python! {
        print("Hi from PyO3")
        foo = 37.46 ## 3
        print(foo)
    }
}
Community
  • 1
  • 1
SCappella
  • 9,534
  • 1
  • 26
  • 35