[go: up one dir, main page]

pyo3 0.14.3

Bindings to Python interpreter
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
use pyo3::exceptions::PyValueError;
use pyo3::prelude::*;
use pyo3::types::{PyDict, PyString, PyTuple};
use pyo3::PyMappingProtocol;

#[macro_use]
mod common;

/// Helper function that concatenates the error message from
/// each error in the traceback into a single string that can
/// be tested.
fn extract_traceback(py: Python, mut error: PyErr) -> String {
    let mut error_msg = error.to_string();
    while let Some(cause) = error.cause(py) {
        error_msg.push_str(": ");
        error_msg.push_str(&cause.to_string());
        error = cause
    }
    error_msg
}

#[derive(Debug, FromPyObject)]
pub struct A<'a> {
    #[pyo3(attribute)]
    s: String,
    #[pyo3(item)]
    t: &'a PyString,
    #[pyo3(attribute("foo"))]
    p: &'a PyAny,
}

#[pyclass]
pub struct PyA {
    #[pyo3(get)]
    s: String,
    #[pyo3(get)]
    foo: Option<String>,
}

#[pyproto]
impl PyMappingProtocol for PyA {
    fn __getitem__(&self, key: String) -> pyo3::PyResult<String> {
        if key == "t" {
            Ok("bar".into())
        } else {
            Err(PyValueError::new_err("Failed"))
        }
    }
}

#[test]
fn test_named_fields_struct() {
    Python::with_gil(|py| {
        let pya = PyA {
            s: "foo".into(),
            foo: None,
        };
        let py_c = Py::new(py, pya).unwrap();
        let a: A = FromPyObject::extract(py_c.as_ref(py)).expect("Failed to extract A from PyA");
        assert_eq!(a.s, "foo");
        assert_eq!(a.t.to_string_lossy(), "bar");
        assert!(a.p.is_none());
    });
}

#[derive(Debug, FromPyObject)]
#[pyo3(transparent)]
pub struct B {
    test: String,
}

#[test]
fn test_transparent_named_field_struct() {
    Python::with_gil(|py| {
        let test = "test".into_py(py);
        let b: B = FromPyObject::extract(test.as_ref(py)).expect("Failed to extract B from String");
        assert_eq!(b.test, "test");
        let test: PyObject = 1.into_py(py);
        let b = B::extract(test.as_ref(py));
        assert!(b.is_err());
    });
}

#[derive(Debug, FromPyObject)]
#[pyo3(transparent)]
pub struct D<T> {
    test: T,
}

#[test]
fn test_generic_transparent_named_field_struct() {
    Python::with_gil(|py| {
        let test = "test".into_py(py);
        let d: D<String> =
            D::extract(test.as_ref(py)).expect("Failed to extract D<String> from String");
        assert_eq!(d.test, "test");
        let test = 1usize.into_py(py);
        let d: D<usize> =
            D::extract(test.as_ref(py)).expect("Failed to extract D<usize> from String");
        assert_eq!(d.test, 1);
    });
}

#[derive(Debug, FromPyObject)]
pub struct E<T, T2> {
    test: T,
    test2: T2,
}

#[pyclass]
#[derive(Clone)]
pub struct PyE {
    #[pyo3(get)]
    test: String,
    #[pyo3(get)]
    test2: usize,
}

#[test]
fn test_generic_named_fields_struct() {
    Python::with_gil(|py| {
        let pye = PyE {
            test: "test".into(),
            test2: 2,
        }
        .into_py(py);

        let e: E<String, usize> =
            E::extract(pye.as_ref(py)).expect("Failed to extract E<String, usize> from PyE");
        assert_eq!(e.test, "test");
        assert_eq!(e.test2, 2);
        let e = E::<usize, usize>::extract(pye.as_ref(py));
        assert!(e.is_err());
    });
}

#[derive(Debug, FromPyObject)]
pub struct C {
    #[pyo3(attribute("test"))]
    test: String,
}

#[test]
fn test_named_field_with_ext_fn() {
    Python::with_gil(|py| {
        let pyc = PyE {
            test: "foo".into(),
            test2: 0,
        }
        .into_py(py);
        let c = C::extract(pyc.as_ref(py)).expect("Failed to extract C from PyE");
        assert_eq!(c.test, "foo");
    });
}

#[derive(Debug, FromPyObject)]
pub struct Tuple(String, usize);

#[test]
fn test_tuple_struct() {
    Python::with_gil(|py| {
        let tup = PyTuple::new(py, &[1.into_py(py), "test".into_py(py)]);
        let tup = Tuple::extract(tup.as_ref());
        assert!(tup.is_err());
        let tup = PyTuple::new(py, &["test".into_py(py), 1.into_py(py)]);
        let tup = Tuple::extract(tup.as_ref()).expect("Failed to extract Tuple from PyTuple");
        assert_eq!(tup.0, "test");
        assert_eq!(tup.1, 1);
    });
}

#[derive(Debug, FromPyObject)]
pub struct TransparentTuple(String);

#[test]
fn test_transparent_tuple_struct() {
    Python::with_gil(|py| {
        let tup: PyObject = 1.into_py(py);
        let tup = TransparentTuple::extract(tup.as_ref(py));
        assert!(tup.is_err());
        let test = "test".into_py(py);
        let tup = TransparentTuple::extract(test.as_ref(py))
            .expect("Failed to extract TransparentTuple from PyTuple");
        assert_eq!(tup.0, "test");
    });
}

#[pyclass]
struct PyBaz {
    #[pyo3(get)]
    tup: (String, String),
    #[pyo3(get)]
    e: PyE,
}

#[derive(Debug, FromPyObject)]
struct Baz<U, T> {
    e: E<U, T>,
    tup: Tuple,
}

#[test]
fn test_struct_nested_type_errors() {
    Python::with_gil(|py| {
        let pybaz = PyBaz {
            tup: ("test".into(), "test".into()),
            e: PyE {
                test: "foo".into(),
                test2: 0,
            },
        }
        .into_py(py);

        let test: PyResult<Baz<String, usize>> = FromPyObject::extract(pybaz.as_ref(py));
        assert!(test.is_err());
        assert_eq!(
            extract_traceback(py,test.unwrap_err()),
            "TypeError: failed to extract field Baz.tup: TypeError: failed to extract field Tuple.1: \
         TypeError: \'str\' object cannot be interpreted as an integer"
        );
    });
}

#[test]
fn test_struct_nested_type_errors_with_generics() {
    Python::with_gil(|py| {
        let pybaz = PyBaz {
            tup: ("test".into(), "test".into()),
            e: PyE {
                test: "foo".into(),
                test2: 0,
            },
        }
        .into_py(py);

        let test: PyResult<Baz<usize, String>> = FromPyObject::extract(pybaz.as_ref(py));
        assert!(test.is_err());
        assert_eq!(
            extract_traceback(py, test.unwrap_err()),
            "TypeError: failed to extract field Baz.e: TypeError: failed to extract field E.test: \
         TypeError: \'str\' object cannot be interpreted as an integer",
        );
    });
}

#[test]
fn test_transparent_struct_error_message() {
    Python::with_gil(|py| {
        let tup: PyObject = 1.into_py(py);
        let tup = B::extract(tup.as_ref(py));
        assert!(tup.is_err());
        assert_eq!(
            extract_traceback(py,tup.unwrap_err()),
            "TypeError: failed to extract field B.test: TypeError: \'int\' object cannot be converted \
         to \'PyString\'"
        );
    });
}

#[test]
fn test_tuple_struct_error_message() {
    Python::with_gil(|py| {
        let tup: PyObject = (1, "test").into_py(py);
        let tup = Tuple::extract(tup.as_ref(py));
        assert!(tup.is_err());
        assert_eq!(
            extract_traceback(py, tup.unwrap_err()),
            "TypeError: failed to extract field Tuple.0: TypeError: \'int\' object cannot be \
         converted to \'PyString\'"
        );
    });
}

#[test]
fn test_transparent_tuple_error_message() {
    Python::with_gil(|py| {
        let tup: PyObject = 1.into_py(py);
        let tup = TransparentTuple::extract(tup.as_ref(py));
        assert!(tup.is_err());
        assert_eq!(
            extract_traceback(py, tup.unwrap_err()),
            "TypeError: failed to extract inner field of TransparentTuple: 'int' object \
         cannot be converted to 'PyString'",
        );
    });
}

#[derive(Debug, FromPyObject)]
pub enum Foo<'a> {
    TupleVar(usize, String),
    StructVar {
        test: &'a PyString,
    },
    #[pyo3(transparent)]
    TransparentTuple(usize),
    #[pyo3(transparent)]
    TransparentStructVar {
        a: Option<String>,
    },
    StructVarGetAttrArg {
        #[pyo3(attribute("bla"))]
        a: bool,
    },
    StructWithGetItem {
        #[pyo3(item)]
        a: String,
    },
    StructWithGetItemArg {
        #[pyo3(item("foo"))]
        a: String,
    },
    #[pyo3(transparent)]
    CatchAll(&'a PyAny),
}

#[pyclass]
pub struct PyBool {
    #[pyo3(get)]
    bla: bool,
}

#[test]
fn test_enum() {
    Python::with_gil(|py| {
        let tup = PyTuple::new(py, &[1.into_py(py), "test".into_py(py)]);
        let f = Foo::extract(tup.as_ref()).expect("Failed to extract Foo from tuple");
        match f {
            Foo::TupleVar(test, test2) => {
                assert_eq!(test, 1);
                assert_eq!(test2, "test");
            }
            _ => panic!("Expected extracting Foo::TupleVar, got {:?}", f),
        }

        let pye = PyE {
            test: "foo".into(),
            test2: 0,
        }
        .into_py(py);
        let f = Foo::extract(pye.as_ref(py)).expect("Failed to extract Foo from PyE");
        match f {
            Foo::StructVar { test } => assert_eq!(test.to_string_lossy(), "foo"),
            _ => panic!("Expected extracting Foo::StructVar, got {:?}", f),
        }

        let int: PyObject = 1.into_py(py);
        let f = Foo::extract(int.as_ref(py)).expect("Failed to extract Foo from int");
        match f {
            Foo::TransparentTuple(test) => assert_eq!(test, 1),
            _ => panic!("Expected extracting Foo::TransparentTuple, got {:?}", f),
        }
        let none = py.None();
        let f = Foo::extract(none.as_ref(py)).expect("Failed to extract Foo from int");
        match f {
            Foo::TransparentStructVar { a } => assert!(a.is_none()),
            _ => panic!("Expected extracting Foo::TransparentStructVar, got {:?}", f),
        }

        let pybool = PyBool { bla: true }.into_py(py);
        let f = Foo::extract(pybool.as_ref(py)).expect("Failed to extract Foo from PyBool");
        match f {
            Foo::StructVarGetAttrArg { a } => assert!(a),
            _ => panic!("Expected extracting Foo::StructVarGetAttrArg, got {:?}", f),
        }

        let dict = PyDict::new(py);
        dict.set_item("a", "test").expect("Failed to set item");
        let f = Foo::extract(dict.as_ref()).expect("Failed to extract Foo from dict");
        match f {
            Foo::StructWithGetItem { a } => assert_eq!(a, "test"),
            _ => panic!("Expected extracting Foo::StructWithGetItem, got {:?}", f),
        }

        let dict = PyDict::new(py);
        dict.set_item("foo", "test").expect("Failed to set item");
        let f = Foo::extract(dict.as_ref()).expect("Failed to extract Foo from dict");
        match f {
            Foo::StructWithGetItemArg { a } => assert_eq!(a, "test"),
            _ => panic!("Expected extracting Foo::StructWithGetItemArg, got {:?}", f),
        }

        let dict = PyDict::new(py);
        let f = Foo::extract(dict.as_ref()).expect("Failed to extract Foo from dict");
        match f {
            Foo::CatchAll(any) => {
                let d = <&PyDict>::extract(any).expect("Expected pydict");
                assert!(d.is_empty());
            }
            _ => panic!("Expected extracting Foo::CatchAll, got {:?}", f),
        }
    });
}

#[derive(Debug, FromPyObject)]
pub enum Bar {
    #[pyo3(annotation = "str")]
    A(String),
    #[pyo3(annotation = "uint")]
    B(usize),
    #[pyo3(annotation = "int", transparent)]
    C(isize),
}

#[test]
fn test_err_rename() {
    Python::with_gil(|py| {
        let dict = PyDict::new(py);
        let f = Bar::extract(dict.as_ref());
        assert!(f.is_err());
        assert_eq!(
            f.unwrap_err().to_string(),
            "TypeError: failed to extract enum Bar (\'Union[str, uint, int]\')\n- variant A (str): \
         \'dict\' object cannot be converted to \'PyString\'\n- variant B (uint): \'dict\' object \
         cannot be interpreted as an integer\n- variant C (int): \'dict\' object cannot be \
         interpreted as an integer\n"
        );
    });
}

#[derive(Debug, FromPyObject)]
pub struct Zap {
    #[pyo3(item)]
    name: String,

    #[pyo3(from_py_with = "PyAny::len", item("my_object"))]
    some_object_length: usize,
}

#[test]
fn test_from_py_with() {
    Python::with_gil(|py| {
        let py_zap = py
            .eval(
                r#"{"name": "whatever", "my_object": [1, 2, 3]}"#,
                None,
                None,
            )
            .expect("failed to create dict");

        let zap = Zap::extract(py_zap).unwrap();

        assert_eq!(zap.name, "whatever");
        assert_eq!(zap.some_object_length, 3usize);
    });
}