Macro python_comm::to_py[][src]

macro_rules! to_py {
    ($py : tt, dict, $obj : tt, $($any : tt), +) => { ... };
    ($py : tt, obj, $obj : tt, $($any : tt), +) => { ... };
    ($func : ident, $py : expr, $obj : expr, [$($any : tt), + $(,) *]) => { ... };
    ($func : ident, $py : expr, $obj : expr, $factory : expr,
 [$($any : tt), + $(,) *]) => { ... };
    ($func : ident, $py : expr, $obj : expr, $factory : expr,
 ($field : expr, $value : expr, Decimal)) => { ... };
    ($func : ident, $py : expr, $obj : expr, $factory : expr,
 ($field : expr, $value : expr, $any : tt)) => { ... };
    ($func : ident, $py : expr, $obj : expr, $factory : expr,
 ($field : expr, $value : expr)) => { ... };
}
Expand description

Set the specified fields in Python dict / obj

Usage

use pyo3::{prepare_freethreaded_python, Python};
use python_comm::{from_py_use::*, raise_error_use::*, to_py_use::*};
use rust_decimal_macros::dec;

prepare_freethreaded_python();

let gil = Python::acquire_gil();
let py = gil.python();

let locals = PyDict::new(py);

let _ = py.run(
    r#"
class Something():
  def __init__(self):
    self.a=1
    self.b=1

class Factory():
  def create_decimal(self, s):
    import decimal  # 真实代码不用在这里 import, 嵌入在 py.run 中时, 其它地方 import 总是失败
    return decimal.Decimal(s)

some = Something()

factory = Factory()
"#,
    None,
    Some(&locals),
).unwrap();

let some: &PyAny = from_py!(dict, locals, "some",).unwrap();
let factory: &PyAny = from_py!(dict, locals, "factory",).unwrap();

let a:i32 = from_py!(obj, some, "a",).unwrap();
assert_eq!(a, 1);

// Usage 1: set the specified field in Python obj, where obj is a keyword
let _ = to_py!(py, obj, some, [
    ("a", 2),
    ("b", 3),
]).unwrap();
let a:i32 = from_py!(obj, some, "a",).unwrap();
assert_eq!(a, 2);

// Usage 2: set the specified field in Python dict, where dict is a keyword

// Usage 3: specify decimal type on the basis of usage 1-2,
// need to provide a factory object that implements create_decimal()
let _ = to_py!(py, obj, some, factory, [
    ("a", dec!(2.5), Decimal)
]).unwrap();
let a = from_py!(obj, some, "a", Decimal).unwrap();
assert_eq!(a, dec!(2.5));

// Note: the decimal module of Python 3.10 supports capsule, 
// which can be created directly instead