Skip to content

Commit de84e08

Browse files
committed
Update to PyO3 0.21.
1 parent be30598 commit de84e08

File tree

8 files changed

+36
-33
lines changed

8 files changed

+36
-33
lines changed

Cargo.toml

+1-1
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,7 @@ autoexamples = false
1414

1515
[dependencies]
1616
inline-python-macros = { version = "=0.12.0", path = "./macros" }
17-
pyo3 = { version = "0.20", default-features = false, features = ["auto-initialize"] }
17+
pyo3 = { version = "0.21", default-features = false, features = ["auto-initialize"] }
1818

1919
[workspace]
2020
members = ["examples", "ct-python"]

examples/Cargo.toml

+1-1
Original file line numberDiff line numberDiff line change
@@ -17,4 +17,4 @@ path = "rust-fn.rs"
1717

1818
[dependencies]
1919
inline-python = { path = ".." }
20-
pyo3 = "0.20"
20+
pyo3 = "0.21"

macros/Cargo.toml

+1-1
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,7 @@ proc_macro = true
1616
[dependencies]
1717
proc-macro2 = { version = "1.0", features = ["span-locations"] }
1818
quote = "1.0"
19-
pyo3 = { version = "0.20", default-features = false, features = ["auto-initialize"] }
19+
pyo3 = { version = "0.21", default-features = false, features = ["auto-initialize"] }
2020

2121
[target.'cfg(unix)'.dependencies]
2222
libc = "0.2.71"

macros/src/error.rs

+7-7
Original file line numberDiff line numberDiff line change
@@ -1,18 +1,18 @@
11
use proc_macro::Span;
22
use proc_macro2::TokenStream;
3-
use pyo3::{PyAny, PyErr, PyResult, PyTypeInfo, Python, ToPyObject};
3+
use pyo3::{prelude::*, types::PyTraceback, Bound, PyErr, PyResult, PyTypeInfo, Python, ToPyObject};
44
use quote::{quote, quote_spanned};
55

66
/// Format a nice error message for a python compilation error.
77
pub fn compile_error_msg(py: Python, error: PyErr, tokens: TokenStream) -> TokenStream {
88
let value = error.to_object(py);
99

1010
if value.is_none(py) {
11-
let error = format!("python: {}", error.get_type(py).name().unwrap());
11+
let error = format!("python: {}", error.get_type_bound(py).name().unwrap());
1212
return quote!(compile_error! {#error});
1313
}
1414

15-
if error.matches(py, pyo3::exceptions::PySyntaxError::type_object(py)) {
15+
if error.matches(py, pyo3::exceptions::PySyntaxError::type_object_bound(py)) {
1616
let line: Option<usize> = value.getattr(py, "lineno").ok().and_then(|x| x.extract(py).ok());
1717
let msg: Option<String> = value.getattr(py, "msg").ok().and_then(|x| x.extract(py).ok());
1818
if let (Some(line), Some(msg)) = (line, msg) {
@@ -23,10 +23,10 @@ pub fn compile_error_msg(py: Python, error: PyErr, tokens: TokenStream) -> Token
2323
}
2424
}
2525

26-
if let Some(tb) = &error.traceback(py) {
26+
if let Some(tb) = &error.traceback_bound(py) {
2727
if let Ok((file, line)) = get_traceback_info(tb) {
2828
if file == Span::call_site().source_file().path().to_string_lossy() {
29-
if let Ok(msg) = value.as_ref(py).str() {
29+
if let Ok(msg) = value.bind(py).str() {
3030
if let Some(span) = span_for_line(tokens, line) {
3131
let error = format!("python: {}", msg);
3232
return quote_spanned!(span.into() => compile_error!{#error});
@@ -36,11 +36,11 @@ pub fn compile_error_msg(py: Python, error: PyErr, tokens: TokenStream) -> Token
3636
}
3737
}
3838

39-
let error = format!("python: {}", value.as_ref(py).str().unwrap());
39+
let error = format!("python: {}", value.bind(py).str().unwrap());
4040
quote!(compile_error! {#error})
4141
}
4242

43-
fn get_traceback_info(tb: &PyAny) -> PyResult<(String, usize)> {
43+
fn get_traceback_info(tb: &Bound<'_, PyTraceback>) -> PyResult<(String, usize)> {
4444
let frame = tb.getattr("tb_frame")?;
4545
let code = frame.getattr("f_code")?;
4646
let file: String = code.getattr("co_filename")?.extract()?;

macros/src/lib.rs

+8-6
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@ extern crate proc_macro;
77
use self::embed_python::EmbedPython;
88
use proc_macro::{Span, TokenStream as TokenStream1};
99
use proc_macro2::{Literal, TokenStream};
10-
use pyo3::{ffi, types::PyBytes, FromPyPointer, PyObject, Python};
10+
use pyo3::{ffi, Py, PyObject, Python};
1111
use quote::quote;
1212
use std::ffi::CString;
1313

@@ -37,9 +37,9 @@ fn python_impl(input: TokenStream) -> Result<TokenStream, TokenStream> {
3737
.map_err(|err| error::compile_error_msg(py, err, tokens))?;
3838

3939
Ok(Literal::byte_string(
40-
PyBytes::from_owned_ptr_or_err(py, ffi::PyMarshal_WriteObjectToString(code.as_ptr(), pyo3::marshal::VERSION))
40+
Py::from_owned_ptr_or_err(py, ffi::PyMarshal_WriteObjectToString(code.as_ptr(), pyo3::marshal::VERSION))
4141
.map_err(|_e| quote!(compile_error! {"failed to generate python bytecode"}))?
42-
.as_bytes(),
42+
.as_bytes(py),
4343
))
4444
});
4545
result?
@@ -53,9 +53,11 @@ fn python_impl(input: TokenStream) -> Result<TokenStream, TokenStream> {
5353
#bytecode,
5454
|globals| {
5555
#(
56-
globals
57-
.set_item(#varname, #var)
58-
.expect("Unable to convert variable to Python");
56+
::inline_python::pyo3::prelude::PyDictMethods::set_item(
57+
globals,
58+
#varname,
59+
#var
60+
).expect("Unable to convert variable to Python");
5961
)*
6062
},
6163
)

macros/src/run.rs

+6-6
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
use crate::error::compile_error_msg;
22
use proc_macro2::TokenStream;
3-
use pyo3::{ffi, PyObject, PyResult, Python};
3+
use pyo3::{ffi, prelude::*, PyObject, PyResult, Python};
44
use std::str::FromStr;
55

66
#[cfg(unix)]
@@ -14,7 +14,7 @@ fn ensure_libpython_symbols_loaded(py: Python) -> PyResult<()> {
1414
// This function tries to (re)load the right version of libpython, but this
1515
// time with RTLD_GLOBAL enabled.
1616

17-
let sysconfig = py.import("sysconfig")?;
17+
let sysconfig = py.import_bound("sysconfig")?;
1818
let libdir: String = sysconfig.getattr("get_config_var")?.call1(("LIBDIR",))?.extract()?;
1919
let so_name: String = sysconfig.getattr("get_config_var")?.call1(("INSTSONAME",))?.extract()?;
2020
let path = std::ffi::CString::new(format!("{}/{}", libdir, so_name)).unwrap();
@@ -28,14 +28,14 @@ fn run_and_capture(py: Python, code: PyObject) -> PyResult<String> {
2828
#[cfg(unix)]
2929
let _ = ensure_libpython_symbols_loaded(py);
3030

31-
let globals = py.import("__main__")?.dict().copy()?;
31+
let globals = py.import_bound("__main__")?.dict().copy()?;
3232

33-
let sys = py.import("sys")?;
34-
let io = py.import("io")?;
33+
let sys = py.import_bound("sys")?;
34+
let io = py.import_bound("io")?;
3535

3636
let stdout = io.getattr("StringIO")?.call0()?;
3737
let original_stdout = sys.dict().get_item("stdout")?;
38-
sys.dict().set_item("stdout", stdout)?;
38+
sys.dict().set_item("stdout", &stdout)?;
3939

4040
let result =
4141
unsafe { PyObject::from_owned_ptr_or_err(py, ffi::PyEval_EvalCode(code.as_ptr(), globals.as_ptr(), std::ptr::null_mut())) };

src/context.rs

+7-6
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
use crate::run::run_python_code;
22
use crate::PythonBlock;
33
use pyo3::{
4+
prelude::*,
45
types::{PyCFunction, PyDict},
56
FromPyObject, Py, PyResult, Python, ToPyObject,
67
};
@@ -70,13 +71,13 @@ impl Context {
7071

7172
fn try_new(py: Python) -> PyResult<Self> {
7273
Ok(Self {
73-
globals: py.import("__main__")?.dict().copy()?.into(),
74+
globals: py.import_bound("__main__")?.dict().copy()?.into(),
7475
})
7576
}
7677

7778
/// Get the globals as dictionary.
78-
pub fn globals<'p>(&'p self, py: Python<'p>) -> &'p PyDict {
79-
self.globals.as_ref(py)
79+
pub fn globals<'p>(&'p self, py: Python<'p>) -> &'p Bound<'p, PyDict> {
80+
self.globals.bind(py)
8081
}
8182

8283
/// Retrieve a global variable from the context.
@@ -95,7 +96,7 @@ impl Context {
9596
pub fn get_with_gil<'p, T: FromPyObject<'p>>(&'p self, py: Python<'p>, name: &str) -> T {
9697
match self.globals(py).get_item(name) {
9798
Err(_) | Ok(None) => panic!("Python context does not contain a variable named `{}`", name),
98-
Ok(Some(value)) => match FromPyObject::extract(value) {
99+
Ok(Some(value)) => match FromPyObject::extract_bound(&value) {
99100
Ok(value) => value,
100101
Err(e) => {
101102
e.print(py);
@@ -184,7 +185,7 @@ impl Context {
184185
/// If you already have the GIL, you can use [`Context::run_with_gil`] instead.
185186
///
186187
/// This function panics if the Python code fails.
187-
pub fn run<F: FnOnce(&PyDict)>(&self, code: PythonBlock<F>) {
188+
pub fn run<F: FnOnce(&Bound<PyDict>)>(&self, code: PythonBlock<F>) {
188189
Python::with_gil(|py| self.run_with_gil(py, code));
189190
}
190191

@@ -194,7 +195,7 @@ impl Context {
194195
/// [`Context::run`].
195196
///
196197
/// This function panics if the Python code fails.
197-
pub fn run_with_gil<F: FnOnce(&PyDict)>(&self, py: Python<'_>, code: PythonBlock<F>) {
198+
pub fn run_with_gil<F: FnOnce(&Bound<PyDict>)>(&self, py: Python<'_>, code: PythonBlock<F>) {
198199
(code.set_variables)(self.globals(py));
199200
match run_python_code(py, self, code.bytecode) {
200201
Ok(_) => (),

src/lib.rs

+5-5
Original file line numberDiff line numberDiff line change
@@ -111,7 +111,7 @@
111111
//!
112112
//! Everything else should work fine.
113113
114-
use pyo3::{types::PyDict, Python};
114+
use pyo3::{types::PyDict, Bound, Python};
115115

116116
mod context;
117117
mod run;
@@ -138,21 +138,21 @@ pub use pyo3;
138138
pub use inline_python_macros::python;
139139

140140
#[doc(hidden)]
141-
pub trait FromInlinePython<F: FnOnce(&PyDict)> {
141+
pub trait FromInlinePython<F: FnOnce(&Bound<PyDict>)> {
142142
fn from_python_macro(bytecode: &'static [u8], set_variables: F) -> Self;
143143
}
144144

145145
/// Converting a `python!{}` block to `()` will run the Python code.
146146
///
147147
/// This happens when `python!{}` is used as a statement by itself.
148-
impl<F: FnOnce(&PyDict)> FromInlinePython<F> for () {
148+
impl<F: FnOnce(&Bound<PyDict>)> FromInlinePython<F> for () {
149149
fn from_python_macro(bytecode: &'static [u8], set_variables: F) {
150150
let _: Context = FromInlinePython::from_python_macro(bytecode, set_variables);
151151
}
152152
}
153153

154154
/// Assigning a `python!{}` block to a `Context` will run the Python code and capture the resulting context.
155-
impl<F: FnOnce(&PyDict)> FromInlinePython<F> for Context {
155+
impl<F: FnOnce(&Bound<PyDict>)> FromInlinePython<F> for Context {
156156
fn from_python_macro(bytecode: &'static [u8], set_variables: F) -> Self {
157157
Python::with_gil(|py| {
158158
let context = Context::new_with_gil(py);
@@ -163,7 +163,7 @@ impl<F: FnOnce(&PyDict)> FromInlinePython<F> for Context {
163163
}
164164

165165
/// Using a `python!{}` block as a `PythonBlock` object will not do anything yet.
166-
impl<F: FnOnce(&PyDict)> FromInlinePython<F> for PythonBlock<F> {
166+
impl<F: FnOnce(&Bound<PyDict>)> FromInlinePython<F> for PythonBlock<F> {
167167
fn from_python_macro(bytecode: &'static [u8], set_variables: F) -> Self {
168168
Self { bytecode, set_variables }
169169
}

0 commit comments

Comments
 (0)