port `Python::import` to `Bound` API (#3832)

* port `Python::import` to `Bound` API

* tidy up imports in tests/test_datetime_import.rs

---------

Co-authored-by: David Hewitt <mail@davidhewitt.dev>
This commit is contained in:
Icxolu 2024-02-14 01:24:37 +01:00 committed by GitHub
parent a1e77c5a66
commit 0c12d9137f
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
26 changed files with 153 additions and 108 deletions

View File

@ -149,10 +149,10 @@ use pyo3::types::IntoPyDict;
fn main() -> PyResult<()> { fn main() -> PyResult<()> {
Python::with_gil(|py| { Python::with_gil(|py| {
let sys = py.import("sys")?; let sys = py.import_bound("sys")?;
let version: String = sys.getattr("version")?.extract()?; let version: String = sys.getattr("version")?.extract()?;
let locals = [("os", py.import("os")?)].into_py_dict_bound(py); let locals = [("os", py.import_bound("os")?)].into_py_dict_bound(py);
let code = "os.getenv('USER') or os.getenv('USERNAME') or 'Unknown'"; let code = "os.getenv('USER') or os.getenv('USERNAME') or 'Unknown'";
let user: String = py.eval_bound(code, None, Some(&locals))?.extract()?; let user: String = py.eval_bound(code, None, Some(&locals))?.extract()?;

View File

@ -414,7 +414,7 @@ fn main() -> PyResult<()> {
let path = Path::new("/usr/share/python_app"); let path = Path::new("/usr/share/python_app");
let py_app = fs::read_to_string(path.join("app.py"))?; let py_app = fs::read_to_string(path.join("app.py"))?;
let from_python = Python::with_gil(|py| -> PyResult<Py<PyAny>> { let from_python = Python::with_gil(|py| -> PyResult<Py<PyAny>> {
let syspath: &PyList = py.import("sys")?.getattr("path")?.downcast()?; let syspath = py.import_bound("sys")?.getattr("path")?.downcast_into::<PyList>()?;
syspath.insert(0, &path)?; syspath.insert(0, &path)?;
let app: Py<PyAny> = PyModule::from_code(py, &py_app, "", "")? let app: Py<PyAny> = PyModule::from_code(py, &py_app, "", "")?
.getattr("run")? .getattr("run")?
@ -498,7 +498,7 @@ use pyo3::prelude::*;
# fn main() -> PyResult<()> { # fn main() -> PyResult<()> {
Python::with_gil(|py| -> PyResult<()> { Python::with_gil(|py| -> PyResult<()> {
let signal = py.import("signal")?; let signal = py.import_bound("signal")?;
// Set SIGINT to have the default action // Set SIGINT to have the default action
signal signal
.getattr("signal")? .getattr("signal")?

View File

@ -689,6 +689,7 @@ impl_element!(f64, Float);
mod tests { mod tests {
use super::PyBuffer; use super::PyBuffer;
use crate::ffi; use crate::ffi;
use crate::types::any::PyAnyMethods;
use crate::Python; use crate::Python;
#[test] #[test]
@ -890,11 +891,11 @@ mod tests {
fn test_array_buffer() { fn test_array_buffer() {
Python::with_gil(|py| { Python::with_gil(|py| {
let array = py let array = py
.import("array") .import_bound("array")
.unwrap() .unwrap()
.call_method("array", ("f", (1.0, 1.5, 2.0, 2.5)), None) .call_method("array", ("f", (1.0, 1.5, 2.0, 2.5)), None)
.unwrap(); .unwrap();
let buffer = PyBuffer::get(array).unwrap(); let buffer = PyBuffer::get(array.as_gil_ref()).unwrap();
assert_eq!(buffer.dimensions(), 1); assert_eq!(buffer.dimensions(), 1);
assert_eq!(buffer.item_count(), 4); assert_eq!(buffer.item_count(), 4);
assert_eq!(buffer.format().to_str().unwrap(), "f"); assert_eq!(buffer.format().to_str().unwrap(), "f");
@ -924,7 +925,7 @@ mod tests {
assert_eq!(buffer.to_vec(py).unwrap(), [10.0, 11.0, 12.0, 13.0]); assert_eq!(buffer.to_vec(py).unwrap(), [10.0, 11.0, 12.0, 13.0]);
// F-contiguous fns // F-contiguous fns
let buffer = PyBuffer::get(array).unwrap(); let buffer = PyBuffer::get(array.as_gil_ref()).unwrap();
let slice = buffer.as_fortran_slice(py).unwrap(); let slice = buffer.as_fortran_slice(py).unwrap();
assert_eq!(slice.len(), 4); assert_eq!(slice.len(), 4);
assert_eq!(slice[1].get(), 11.0); assert_eq!(slice[1].get(), 11.0);

View File

@ -540,15 +540,15 @@ impl DatetimeTypes {
static TYPES: GILOnceCell<DatetimeTypes> = GILOnceCell::new(); static TYPES: GILOnceCell<DatetimeTypes> = GILOnceCell::new();
TYPES TYPES
.get_or_try_init(py, || { .get_or_try_init(py, || {
let datetime = py.import("datetime")?; let datetime = py.import_bound("datetime")?;
let timezone = datetime.getattr("timezone")?; let timezone = datetime.getattr("timezone")?;
Ok::<_, PyErr>(Self { Ok::<_, PyErr>(Self {
date: datetime.getattr("date")?.into(), date: datetime.getattr("date")?.into(),
datetime: datetime.getattr("datetime")?.into(), datetime: datetime.getattr("datetime")?.into(),
time: datetime.getattr("time")?.into(), time: datetime.getattr("time")?.into(),
timedelta: datetime.getattr("timedelta")?.into(), timedelta: datetime.getattr("timedelta")?.into(),
timezone: timezone.into(),
timezone_utc: timezone.getattr("utc")?.into(), timezone_utc: timezone.getattr("utc")?.into(),
timezone: timezone.into(),
tzinfo: datetime.getattr("tzinfo")?.into(), tzinfo: datetime.getattr("tzinfo")?.into(),
}) })
}) })
@ -683,7 +683,7 @@ mod tests {
let delta = delta.to_object(py); let delta = delta.to_object(py);
let py_delta = new_py_datetime_ob(py, "timedelta", (py_days, py_seconds, py_ms)); let py_delta = new_py_datetime_ob(py, "timedelta", (py_days, py_seconds, py_ms));
assert!( assert!(
delta.as_ref(py).eq(py_delta).unwrap(), delta.bind(py).eq(&py_delta).unwrap(),
"{}: {} != {}", "{}: {} != {}",
name, name,
delta, delta,
@ -779,7 +779,7 @@ mod tests {
.to_object(py); .to_object(py);
let py_date = new_py_datetime_ob(py, "date", (year, month, day)); let py_date = new_py_datetime_ob(py, "date", (year, month, day));
assert_eq!( assert_eq!(
date.as_ref(py).compare(py_date).unwrap(), date.bind(py).compare(&py_date).unwrap(),
Ordering::Equal, Ordering::Equal,
"{}: {} != {}", "{}: {} != {}",
name, name,
@ -838,7 +838,7 @@ mod tests {
), ),
); );
assert_eq!( assert_eq!(
datetime.as_ref(py).compare(py_datetime).unwrap(), datetime.bind(py).compare(&py_datetime).unwrap(),
Ordering::Equal, Ordering::Equal,
"{}: {} != {}", "{}: {} != {}",
name, name,
@ -880,7 +880,7 @@ mod tests {
(year, month, day, hour, minute, second, py_ms, py_tz), (year, month, day, hour, minute, second, py_ms, py_tz),
); );
assert_eq!( assert_eq!(
datetime.as_ref(py).compare(py_datetime).unwrap(), datetime.bind(py).compare(&py_datetime).unwrap(),
Ordering::Equal, Ordering::Equal,
"{}: {} != {}", "{}: {} != {}",
name, name,
@ -1005,7 +1005,7 @@ mod tests {
Python::with_gil(|py| { Python::with_gil(|py| {
let utc = Utc.to_object(py); let utc = Utc.to_object(py);
let py_utc = python_utc(py); let py_utc = python_utc(py);
assert!(utc.as_ref(py).is(py_utc)); assert!(utc.bind(py).is(&py_utc));
}) })
} }
@ -1036,7 +1036,7 @@ mod tests {
.to_object(py); .to_object(py);
let py_time = new_py_datetime_ob(py, "time", (hour, minute, second, py_ms)); let py_time = new_py_datetime_ob(py, "time", (hour, minute, second, py_ms));
assert!( assert!(
time.as_ref(py).eq(py_time).unwrap(), time.bind(py).eq(&py_time).unwrap(),
"{}: {} != {}", "{}: {} != {}",
name, name,
time, time,
@ -1071,12 +1071,12 @@ mod tests {
}) })
} }
fn new_py_datetime_ob<'a>( fn new_py_datetime_ob<'py>(
py: Python<'a>, py: Python<'py>,
name: &str, name: &str,
args: impl IntoPy<Py<PyTuple>>, args: impl IntoPy<Py<PyTuple>>,
) -> &'a PyAny { ) -> Bound<'py, PyAny> {
py.import("datetime") py.import_bound("datetime")
.unwrap() .unwrap()
.getattr(name) .getattr(name)
.unwrap() .unwrap()
@ -1084,8 +1084,8 @@ mod tests {
.unwrap() .unwrap()
} }
fn python_utc(py: Python<'_>) -> &PyAny { fn python_utc(py: Python<'_>) -> Bound<'_, PyAny> {
py.import("datetime") py.import_bound("datetime")
.unwrap() .unwrap()
.getattr("timezone") .getattr("timezone")
.unwrap() .unwrap()
@ -1108,7 +1108,7 @@ mod tests {
fn test_pyo3_offset_fixed_frompyobject_created_in_python(timestamp in 0..(i32::MAX as i64), timedelta in -86399i32..=86399i32) { fn test_pyo3_offset_fixed_frompyobject_created_in_python(timestamp in 0..(i32::MAX as i64), timedelta in -86399i32..=86399i32) {
Python::with_gil(|py| { Python::with_gil(|py| {
let globals = [("datetime", py.import("datetime").unwrap())].into_py_dict_bound(py); let globals = [("datetime", py.import_bound("datetime").unwrap())].into_py_dict_bound(py);
let code = format!("datetime.datetime.fromtimestamp({}).replace(tzinfo=datetime.timezone(datetime.timedelta(seconds={})))", timestamp, timedelta); let code = format!("datetime.datetime.fromtimestamp({}).replace(tzinfo=datetime.timezone(datetime.timedelta(seconds={})))", timestamp, timedelta);
let t = py.eval_bound(&code, Some(&globals), None).unwrap(); let t = py.eval_bound(&code, Some(&globals), None).unwrap();

View File

@ -89,8 +89,8 @@ mod tests {
#[test] #[test]
fn test_topyobject() { fn test_topyobject() {
Python::with_gil(|py| { Python::with_gil(|py| {
let assert_eq = |l: PyObject, r: &PyAny| { let assert_eq = |l: PyObject, r: Bound<'_, PyAny>| {
assert!(l.as_ref(py).eq(r).unwrap()); assert!(l.bind(py).eq(r).unwrap());
}; };
assert_eq( assert_eq(
@ -105,11 +105,14 @@ mod tests {
}); });
} }
fn new_zoneinfo<'a>(py: Python<'a>, name: &str) -> &'a PyAny { fn new_zoneinfo<'py>(py: Python<'py>, name: &str) -> Bound<'py, PyAny> {
zoneinfo_class(py).call1((name,)).unwrap() zoneinfo_class(py).call1((name,)).unwrap()
} }
fn zoneinfo_class(py: Python<'_>) -> &PyAny { fn zoneinfo_class(py: Python<'_>) -> Bound<'_, PyAny> {
py.import("zoneinfo").unwrap().getattr("ZoneInfo").unwrap() py.import_bound("zoneinfo")
.unwrap()
.getattr("ZoneInfo")
.unwrap()
} }
} }

View File

@ -77,7 +77,7 @@ static DECIMAL_CLS: GILOnceCell<Py<PyType>> = GILOnceCell::new();
fn get_decimal_cls(py: Python<'_>) -> PyResult<&PyType> { fn get_decimal_cls(py: Python<'_>) -> PyResult<&PyType> {
DECIMAL_CLS DECIMAL_CLS
.get_or_try_init(py, || { .get_or_try_init(py, || {
py.import(intern!(py, "decimal"))? py.import_bound(intern!(py, "decimal"))?
.getattr(intern!(py, "Decimal"))? .getattr(intern!(py, "Decimal"))?
.extract() .extract()
}) })

View File

@ -146,7 +146,7 @@ fn unix_epoch_py(py: Python<'_>) -> &PyObject {
} }
#[cfg(Py_LIMITED_API)] #[cfg(Py_LIMITED_API)]
{ {
let datetime = py.import("datetime")?; let datetime = py.import_bound("datetime")?;
let utc = datetime.getattr("timezone")?.getattr("utc")?; let utc = datetime.getattr("timezone")?.getattr("utc")?;
Ok::<_, PyErr>( Ok::<_, PyErr>(
datetime datetime
@ -216,8 +216,8 @@ mod tests {
#[test] #[test]
fn test_duration_topyobject() { fn test_duration_topyobject() {
Python::with_gil(|py| { Python::with_gil(|py| {
let assert_eq = |l: PyObject, r: &PyAny| { let assert_eq = |l: PyObject, r: Bound<'_, PyAny>| {
assert!(l.as_ref(py).eq(r).unwrap()); assert!(l.bind(py).eq(r).unwrap());
}; };
assert_eq( assert_eq(
@ -300,8 +300,8 @@ mod tests {
#[test] #[test]
fn test_time_topyobject() { fn test_time_topyobject() {
Python::with_gil(|py| { Python::with_gil(|py| {
let assert_eq = |l: PyObject, r: &PyAny| { let assert_eq = |l: PyObject, r: Bound<'_, PyAny>| {
assert!(l.as_ref(py).eq(r).unwrap()); assert!(l.bind(py).eq(r).unwrap());
}; };
assert_eq( assert_eq(
@ -331,7 +331,7 @@ mod tests {
minute: u8, minute: u8,
second: u8, second: u8,
microsecond: u32, microsecond: u32,
) -> &PyAny { ) -> Bound<'_, PyAny> {
datetime_class(py) datetime_class(py)
.call1(( .call1((
year, year,
@ -346,13 +346,11 @@ mod tests {
.unwrap() .unwrap()
} }
fn max_datetime(py: Python<'_>) -> &PyAny { fn max_datetime(py: Python<'_>) -> Bound<'_, PyAny> {
let naive_max = datetime_class(py).getattr("max").unwrap(); let naive_max = datetime_class(py).getattr("max").unwrap();
let kargs = PyDict::new_bound(py); let kargs = PyDict::new_bound(py);
kargs.set_item("tzinfo", tz_utc(py)).unwrap(); kargs.set_item("tzinfo", tz_utc(py)).unwrap();
naive_max naive_max.call_method("replace", (), Some(&kargs)).unwrap()
.call_method("replace", (), Some(kargs.as_gil_ref()))
.unwrap()
} }
#[test] #[test]
@ -365,8 +363,8 @@ mod tests {
}) })
} }
fn tz_utc(py: Python<'_>) -> &PyAny { fn tz_utc(py: Python<'_>) -> Bound<'_, PyAny> {
py.import("datetime") py.import_bound("datetime")
.unwrap() .unwrap()
.getattr("timezone") .getattr("timezone")
.unwrap() .unwrap()
@ -374,17 +372,28 @@ mod tests {
.unwrap() .unwrap()
} }
fn new_timedelta(py: Python<'_>, days: i32, seconds: i32, microseconds: i32) -> &PyAny { fn new_timedelta(
py: Python<'_>,
days: i32,
seconds: i32,
microseconds: i32,
) -> Bound<'_, PyAny> {
timedelta_class(py) timedelta_class(py)
.call1((days, seconds, microseconds)) .call1((days, seconds, microseconds))
.unwrap() .unwrap()
} }
fn datetime_class(py: Python<'_>) -> &PyAny { fn datetime_class(py: Python<'_>) -> Bound<'_, PyAny> {
py.import("datetime").unwrap().getattr("datetime").unwrap() py.import_bound("datetime")
.unwrap()
.getattr("datetime")
.unwrap()
} }
fn timedelta_class(py: Python<'_>) -> &PyAny { fn timedelta_class(py: Python<'_>) -> Bound<'_, PyAny> {
py.import("datetime").unwrap().getattr("timedelta").unwrap() py.import_bound("datetime")
.unwrap()
.getattr("timedelta")
.unwrap()
} }
} }

View File

@ -1,4 +1,5 @@
use crate::sync::GILOnceCell; use crate::sync::GILOnceCell;
use crate::types::any::PyAnyMethods;
use crate::types::PyCFunction; use crate::types::PyCFunction;
use crate::{intern, wrap_pyfunction, Py, PyAny, PyObject, PyResult, Python}; use crate::{intern, wrap_pyfunction, Py, PyAny, PyObject, PyResult, Python};
use pyo3_macros::pyfunction; use pyo3_macros::pyfunction;
@ -56,7 +57,7 @@ impl LoopAndFuture {
fn new(py: Python<'_>) -> PyResult<Self> { fn new(py: Python<'_>) -> PyResult<Self> {
static GET_RUNNING_LOOP: GILOnceCell<PyObject> = GILOnceCell::new(); static GET_RUNNING_LOOP: GILOnceCell<PyObject> = GILOnceCell::new();
let import = || -> PyResult<_> { let import = || -> PyResult<_> {
let module = py.import("asyncio")?; let module = py.import_bound("asyncio")?;
Ok(module.getattr("get_running_loop")?.into()) Ok(module.getattr("get_running_loop")?.into())
}; };
let event_loop = GET_RUNNING_LOOP.get_or_try_init(py, import)?.call0(py)?; let event_loop = GET_RUNNING_LOOP.get_or_try_init(py, import)?.call0(py)?;

View File

@ -974,6 +974,7 @@ impl_signed_integer!(isize);
mod tests { mod tests {
use super::PyErrState; use super::PyErrState;
use crate::exceptions::{self, PyTypeError, PyValueError}; use crate::exceptions::{self, PyTypeError, PyValueError};
use crate::types::any::PyAnyMethods;
use crate::{PyErr, PyTypeInfo, Python}; use crate::{PyErr, PyTypeInfo, Python};
#[test] #[test]
@ -1174,7 +1175,7 @@ mod tests {
let cls = py.get_type::<exceptions::PyUserWarning>(); let cls = py.get_type::<exceptions::PyUserWarning>();
// Reset warning filter to default state // Reset warning filter to default state
let warnings = py.import("warnings").unwrap(); let warnings = py.import_bound("warnings").unwrap();
warnings.call_method0("resetwarnings").unwrap(); warnings.call_method0("resetwarnings").unwrap();
// First, test the warning is emitted // First, test the warning is emitted

View File

@ -101,13 +101,14 @@ macro_rules! import_exception {
fn type_object_raw(py: $crate::Python<'_>) -> *mut $crate::ffi::PyTypeObject { fn type_object_raw(py: $crate::Python<'_>) -> *mut $crate::ffi::PyTypeObject {
use $crate::sync::GILOnceCell; use $crate::sync::GILOnceCell;
use $crate::prelude::PyTracebackMethods; use $crate::prelude::PyTracebackMethods;
use $crate::prelude::PyAnyMethods;
static TYPE_OBJECT: GILOnceCell<$crate::Py<$crate::types::PyType>> = static TYPE_OBJECT: GILOnceCell<$crate::Py<$crate::types::PyType>> =
GILOnceCell::new(); GILOnceCell::new();
TYPE_OBJECT TYPE_OBJECT
.get_or_init(py, || { .get_or_init(py, || {
let imp = py let imp = py
.import(stringify!($module)) .import_bound(stringify!($module))
.unwrap_or_else(|err| { .unwrap_or_else(|err| {
let traceback = err let traceback = err
.traceback_bound(py) .traceback_bound(py)
@ -812,7 +813,7 @@ mod tests {
Python::with_gil(|py| { Python::with_gil(|py| {
let err: PyErr = gaierror::new_err(()); let err: PyErr = gaierror::new_err(());
let socket = py let socket = py
.import("socket") .import_bound("socket")
.map_err(|e| e.display(py)) .map_err(|e| e.display(py))
.expect("could not import socket"); .expect("could not import socket");
@ -836,7 +837,7 @@ mod tests {
Python::with_gil(|py| { Python::with_gil(|py| {
let err: PyErr = MessageError::new_err(()); let err: PyErr = MessageError::new_err(());
let email = py let email = py
.import("email") .import_bound("email")
.map_err(|e| e.display(py)) .map_err(|e| e.display(py))
.expect("could not import email"); .expect("could not import email");

View File

@ -143,7 +143,7 @@ where
// Import the threading module - this ensures that it will associate this thread as the "main" // Import the threading module - this ensures that it will associate this thread as the "main"
// thread, which is important to avoid an `AssertionError` at finalization. // thread, which is important to avoid an `AssertionError` at finalization.
pool.python().import("threading").unwrap(); pool.python().import_bound("threading").unwrap();
// Execute the closure. // Execute the closure.
let result = f(pool.python()); let result = f(pool.python());

View File

@ -67,13 +67,14 @@ impl ModuleDef {
pub fn make_module(&'static self, py: Python<'_>) -> PyResult<Py<PyModule>> { pub fn make_module(&'static self, py: Python<'_>) -> PyResult<Py<PyModule>> {
#[cfg(all(PyPy, not(Py_3_8)))] #[cfg(all(PyPy, not(Py_3_8)))]
{ {
use crate::types::any::PyAnyMethods;
const PYPY_GOOD_VERSION: [u8; 3] = [7, 3, 8]; const PYPY_GOOD_VERSION: [u8; 3] = [7, 3, 8];
let version = py let version = py
.import("sys")? .import_bound("sys")?
.getattr("implementation")? .getattr("implementation")?
.getattr("version")?; .getattr("version")?;
if version.lt(crate::types::PyTuple::new_bound(py, PYPY_GOOD_VERSION))? { if version.lt(crate::types::PyTuple::new_bound(py, PYPY_GOOD_VERSION))? {
let warn = py.import("warnings")?.getattr("warn")?; let warn = py.import_bound("warnings")?.getattr("warn")?;
warn.call1(( warn.call1((
"PyPy 3.7 versions older than 7.3.8 are known to have binary \ "PyPy 3.7 versions older than 7.3.8 are known to have binary \
compatibility issues which may cause segfaults. Please upgrade.", compatibility issues which may cause segfaults. Please upgrade.",
@ -202,7 +203,8 @@ mod tests {
assert_eq!((*module_def.ffi_def.get()).m_doc, DOC.as_ptr() as _); assert_eq!((*module_def.ffi_def.get()).m_doc, DOC.as_ptr() as _);
Python::with_gil(|py| { Python::with_gil(|py| {
module_def.initializer.0(py, py.import("builtins").unwrap()).unwrap(); module_def.initializer.0(py, py.import_bound("builtins").unwrap().into_gil_ref())
.unwrap();
assert!(INIT_CALLED.load(Ordering::SeqCst)); assert!(INIT_CALLED.load(Ordering::SeqCst));
}) })
} }

View File

@ -1196,7 +1196,7 @@ impl<T> Py<T> {
/// # Example: `intern!`ing the attribute name /// # Example: `intern!`ing the attribute name
/// ///
/// ``` /// ```
/// # use pyo3::{intern, pyfunction, types::PyModule, IntoPy, Py, Python, PyObject, PyResult}; /// # use pyo3::{prelude::*, intern};
/// # /// #
/// #[pyfunction] /// #[pyfunction]
/// fn version(sys: Py<PyModule>, py: Python<'_>) -> PyResult<PyObject> { /// fn version(sys: Py<PyModule>, py: Python<'_>) -> PyResult<PyObject> {
@ -1204,7 +1204,7 @@ impl<T> Py<T> {
/// } /// }
/// # /// #
/// # Python::with_gil(|py| { /// # Python::with_gil(|py| {
/// # let sys = py.import("sys").unwrap().into_py(py); /// # let sys = py.import_bound("sys").unwrap().unbind();
/// # version(sys, py).unwrap(); /// # version(sys, py).unwrap();
/// # }); /// # });
/// ``` /// ```

View File

@ -218,10 +218,10 @@
//! //!
//! fn main() -> PyResult<()> { //! fn main() -> PyResult<()> {
//! Python::with_gil(|py| { //! Python::with_gil(|py| {
//! let sys = py.import("sys")?; //! let sys = py.import_bound("sys")?;
//! let version: String = sys.getattr("version")?.extract()?; //! let version: String = sys.getattr("version")?.extract()?;
//! //!
//! let locals = [("os", py.import("os")?)].into_py_dict_bound(py); //! let locals = [("os", py.import_bound("os")?)].into_py_dict_bound(py);
//! let code = "os.getenv('USER') or os.getenv('USERNAME') or 'Unknown'"; //! let code = "os.getenv('USER') or os.getenv('USERNAME') or 'Unknown'";
//! let user: String = py.eval_bound(code, None, Some(&locals))?.extract()?; //! let user: String = py.eval_bound(code, None, Some(&locals))?.extract()?;
//! //!

View File

@ -736,7 +736,14 @@ impl<'py> Python<'py> {
T::type_object_bound(self).into_gil_ref() T::type_object_bound(self).into_gil_ref()
} }
/// Imports the Python module with the specified name. /// Deprecated form of [`Python::import_bound`]
#[cfg_attr(
not(feature = "gil-refs"),
deprecated(
since = "0.21.0",
note = "`Python::import` will be replaced by `Python::import_bound` in a future PyO3 version"
)
)]
pub fn import<N>(self, name: N) -> PyResult<&'py PyModule> pub fn import<N>(self, name: N) -> PyResult<&'py PyModule>
where where
N: IntoPy<Py<PyString>>, N: IntoPy<Py<PyString>>,
@ -744,6 +751,18 @@ impl<'py> Python<'py> {
PyModule::import(self, name) PyModule::import(self, name)
} }
/// Imports the Python module with the specified name.
pub fn import_bound<N>(self, name: N) -> PyResult<Bound<'py, PyModule>>
where
N: IntoPy<Py<PyString>>,
{
// FIXME: This should be replaced by `PyModule::import_bound` once thats
// implemented.
PyModule::import(self, name)
.map(PyNativeType::as_borrowed)
.map(crate::Borrowed::to_owned)
}
/// Gets the Python builtin value `None`. /// Gets the Python builtin value `None`.
#[allow(non_snake_case)] // the Python keyword starts with uppercase #[allow(non_snake_case)] // the Python keyword starts with uppercase
#[inline] #[inline]

View File

@ -1,5 +1,8 @@
//! Synchronization mechanisms based on the Python GIL. //! Synchronization mechanisms based on the Python GIL.
use crate::{types::PyString, types::PyType, Bound, Py, PyResult, PyVisit, Python}; use crate::{
types::{any::PyAnyMethods, PyString, PyType},
Bound, Py, PyResult, PyVisit, Python,
};
use std::cell::UnsafeCell; use std::cell::UnsafeCell;
/// Value with concurrent access protected by the GIL. /// Value with concurrent access protected by the GIL.
@ -197,7 +200,9 @@ impl GILOnceCell<Py<PyType>> {
module_name: &str, module_name: &str,
attr_name: &str, attr_name: &str,
) -> PyResult<&Bound<'py, PyType>> { ) -> PyResult<&Bound<'py, PyType>> {
self.get_or_try_init(py, || py.import(module_name)?.getattr(attr_name)?.extract()) self.get_or_try_init(py, || {
py.import_bound(module_name)?.getattr(attr_name)?.extract()
})
.map(|ty| ty.bind(py)) .map(|ty| ty.bind(py))
} }
} }

View File

@ -83,7 +83,7 @@ mod inner {
#[cfg(all(feature = "macros", Py_3_8))] #[cfg(all(feature = "macros", Py_3_8))]
impl UnraisableCapture { impl UnraisableCapture {
pub fn install(py: Python<'_>) -> Py<Self> { pub fn install(py: Python<'_>) -> Py<Self> {
let sys = py.import("sys").unwrap(); let sys = py.import_bound("sys").unwrap();
let old_hook = sys.getattr("unraisablehook").unwrap().into(); let old_hook = sys.getattr("unraisablehook").unwrap().into();
let capture = Py::new( let capture = Py::new(
@ -104,22 +104,22 @@ mod inner {
pub fn uninstall(&mut self, py: Python<'_>) { pub fn uninstall(&mut self, py: Python<'_>) {
let old_hook = self.old_hook.take().unwrap(); let old_hook = self.old_hook.take().unwrap();
let sys = py.import("sys").unwrap(); let sys = py.import_bound("sys").unwrap();
sys.setattr("unraisablehook", old_hook).unwrap(); sys.setattr("unraisablehook", old_hook).unwrap();
} }
} }
pub struct CatchWarnings<'py> { pub struct CatchWarnings<'py> {
catch_warnings: &'py PyAny, catch_warnings: Bound<'py, PyAny>,
} }
impl<'py> CatchWarnings<'py> { impl<'py> CatchWarnings<'py> {
pub fn enter<R>(py: Python<'py>, f: impl FnOnce(&PyList) -> PyResult<R>) -> PyResult<R> { pub fn enter<R>(py: Python<'py>, f: impl FnOnce(&PyList) -> PyResult<R>) -> PyResult<R> {
let warnings = py.import("warnings")?; let warnings = py.import_bound("warnings")?;
let kwargs = [("record", true)].into_py_dict_bound(py); let kwargs = [("record", true)].into_py_dict_bound(py);
let catch_warnings = warnings let catch_warnings = warnings
.getattr("catch_warnings")? .getattr("catch_warnings")?
.call((), Some(kwargs.as_gil_ref()))?; .call((), Some(&kwargs))?;
let list = catch_warnings.call_method0("__enter__")?.extract()?; let list = catch_warnings.call_method0("__enter__")?.extract()?;
let _guard = Self { catch_warnings }; let _guard = Self { catch_warnings };
f(list) f(list)

View File

@ -86,16 +86,16 @@ impl PyAny {
/// # Example: `intern!`ing the attribute name /// # Example: `intern!`ing the attribute name
/// ///
/// ``` /// ```
/// # use pyo3::{intern, pyfunction, types::PyModule, Python, PyResult}; /// # use pyo3::{prelude::*, intern};
/// # /// #
/// #[pyfunction] /// #[pyfunction]
/// fn has_version(sys: &PyModule) -> PyResult<bool> { /// fn has_version(sys: &Bound<'_, PyModule>) -> PyResult<bool> {
/// sys.hasattr(intern!(sys.py(), "version")) /// sys.hasattr(intern!(sys.py(), "version"))
/// } /// }
/// # /// #
/// # Python::with_gil(|py| { /// # Python::with_gil(|py| {
/// # let sys = py.import("sys").unwrap(); /// # let sys = py.import_bound("sys").unwrap();
/// # has_version(sys).unwrap(); /// # has_version(&sys).unwrap();
/// # }); /// # });
/// ``` /// ```
pub fn hasattr<N>(&self, attr_name: N) -> PyResult<bool> pub fn hasattr<N>(&self, attr_name: N) -> PyResult<bool>
@ -115,16 +115,16 @@ impl PyAny {
/// # Example: `intern!`ing the attribute name /// # Example: `intern!`ing the attribute name
/// ///
/// ``` /// ```
/// # use pyo3::{intern, pyfunction, types::PyModule, PyAny, Python, PyResult}; /// # use pyo3::{prelude::*, intern};
/// # /// #
/// #[pyfunction] /// #[pyfunction]
/// fn version(sys: &PyModule) -> PyResult<&PyAny> { /// fn version<'py>(sys: &Bound<'py, PyModule>) -> PyResult<Bound<'py, PyAny>> {
/// sys.getattr(intern!(sys.py(), "version")) /// sys.getattr(intern!(sys.py(), "version"))
/// } /// }
/// # /// #
/// # Python::with_gil(|py| { /// # Python::with_gil(|py| {
/// # let sys = py.import("sys").unwrap(); /// # let sys = py.import_bound("sys").unwrap();
/// # version(sys).unwrap(); /// # version(&sys).unwrap();
/// # }); /// # });
/// ``` /// ```
pub fn getattr<N>(&self, attr_name: N) -> PyResult<&PyAny> pub fn getattr<N>(&self, attr_name: N) -> PyResult<&PyAny>
@ -956,16 +956,16 @@ pub trait PyAnyMethods<'py> {
/// # Example: `intern!`ing the attribute name /// # Example: `intern!`ing the attribute name
/// ///
/// ``` /// ```
/// # use pyo3::{intern, pyfunction, types::PyModule, Python, PyResult}; /// # use pyo3::{prelude::*, intern};
/// # /// #
/// #[pyfunction] /// #[pyfunction]
/// fn has_version(sys: &PyModule) -> PyResult<bool> { /// fn has_version(sys: &Bound<'_, PyModule>) -> PyResult<bool> {
/// sys.hasattr(intern!(sys.py(), "version")) /// sys.hasattr(intern!(sys.py(), "version"))
/// } /// }
/// # /// #
/// # Python::with_gil(|py| { /// # Python::with_gil(|py| {
/// # let sys = py.import("sys").unwrap(); /// # let sys = py.import_bound("sys").unwrap();
/// # has_version(sys).unwrap(); /// # has_version(&sys).unwrap();
/// # }); /// # });
/// ``` /// ```
fn hasattr<N>(&self, attr_name: N) -> PyResult<bool> fn hasattr<N>(&self, attr_name: N) -> PyResult<bool>
@ -982,16 +982,16 @@ pub trait PyAnyMethods<'py> {
/// # Example: `intern!`ing the attribute name /// # Example: `intern!`ing the attribute name
/// ///
/// ``` /// ```
/// # use pyo3::{intern, pyfunction, types::PyModule, PyAny, Python, PyResult}; /// # use pyo3::{prelude::*, intern};
/// # /// #
/// #[pyfunction] /// #[pyfunction]
/// fn version(sys: &PyModule) -> PyResult<&PyAny> { /// fn version<'py>(sys: &Bound<'py, PyModule>) -> PyResult<Bound<'py, PyAny>> {
/// sys.getattr(intern!(sys.py(), "version")) /// sys.getattr(intern!(sys.py(), "version"))
/// } /// }
/// # /// #
/// # Python::with_gil(|py| { /// # Python::with_gil(|py| {
/// # let sys = py.import("sys").unwrap(); /// # let sys = py.import_bound("sys").unwrap();
/// # version(sys).unwrap(); /// # version(&sys).unwrap();
/// # }); /// # });
/// ``` /// ```
fn getattr<N>(&self, attr_name: N) -> PyResult<Bound<'py, PyAny>> fn getattr<N>(&self, attr_name: N) -> PyResult<Bound<'py, PyAny>>

View File

@ -3,6 +3,9 @@ use crate::types::PyString;
use crate::{ffi, Bound}; use crate::{ffi, Bound};
use crate::{PyAny, PyNativeType}; use crate::{PyAny, PyNativeType};
use super::any::PyAnyMethods;
use super::string::PyStringMethods;
/// Represents a Python traceback. /// Represents a Python traceback.
#[repr(transparent)] #[repr(transparent)]
pub struct PyTraceback(PyAny); pub struct PyTraceback(PyAny);
@ -95,7 +98,7 @@ impl<'py> PyTracebackMethods<'py> for Bound<'py, PyTraceback> {
fn format(&self) -> PyResult<String> { fn format(&self) -> PyResult<String> {
let py = self.py(); let py = self.py();
let string_io = py let string_io = py
.import(intern!(py, "io"))? .import_bound(intern!(py, "io"))?
.getattr(intern!(py, "StringIO"))? .getattr(intern!(py, "StringIO"))?
.call0()?; .call0()?;
let result = unsafe { ffi::PyTraceBack_Print(self.as_ptr(), string_io.as_ptr()) }; let result = unsafe { ffi::PyTraceBack_Print(self.as_ptr(), string_io.as_ptr()) };
@ -104,8 +107,8 @@ impl<'py> PyTracebackMethods<'py> for Bound<'py, PyTraceback> {
.getattr(intern!(py, "getvalue"))? .getattr(intern!(py, "getvalue"))?
.call0()? .call0()?
.downcast::<PyString>()? .downcast::<PyString>()?
.to_str()? .to_cow()?
.to_owned(); .into_owned();
Ok(formatted) Ok(formatted)
} }
} }

View File

@ -101,16 +101,16 @@ fn test_fallible_class_attribute() {
use pyo3::{exceptions::PyValueError, types::PyString}; use pyo3::{exceptions::PyValueError, types::PyString};
struct CaptureStdErr<'py> { struct CaptureStdErr<'py> {
oldstderr: &'py PyAny, oldstderr: Bound<'py, PyAny>,
string_io: &'py PyAny, string_io: Bound<'py, PyAny>,
} }
impl<'py> CaptureStdErr<'py> { impl<'py> CaptureStdErr<'py> {
fn new(py: Python<'py>) -> PyResult<Self> { fn new(py: Python<'py>) -> PyResult<Self> {
let sys = py.import("sys")?; let sys = py.import_bound("sys")?;
let oldstderr = sys.getattr("stderr")?; let oldstderr = sys.getattr("stderr")?;
let string_io = py.import("io")?.getattr("StringIO")?.call0()?; let string_io = py.import_bound("io")?.getattr("StringIO")?.call0()?;
sys.setattr("stderr", string_io)?; sys.setattr("stderr", &string_io)?;
Ok(Self { Ok(Self {
oldstderr, oldstderr,
string_io, string_io,
@ -124,9 +124,9 @@ fn test_fallible_class_attribute() {
.getattr("getvalue")? .getattr("getvalue")?
.call0()? .call0()?
.downcast::<PyString>()? .downcast::<PyString>()?
.to_str()? .to_cow()?
.to_owned(); .into_owned();
let sys = py.import("sys")?; let sys = py.import_bound("sys")?;
sys.setattr("stderr", self.oldstderr)?; sys.setattr("stderr", self.oldstderr)?;
Ok(payload) Ok(payload)
} }

View File

@ -127,7 +127,7 @@ fn cancelled_coroutine() {
await task await task
asyncio.run(main()) asyncio.run(main())
"#; "#;
let globals = gil.import("__main__").unwrap().dict().as_borrowed(); let globals = gil.import_bound("__main__").unwrap().dict();
globals.set_item("sleep", sleep).unwrap(); globals.set_item("sleep", sleep).unwrap();
let err = gil let err = gil
.run_bound( .run_bound(
@ -166,7 +166,7 @@ fn coroutine_cancel_handle() {
return await task return await task
assert asyncio.run(main()) == 0 assert asyncio.run(main()) == 0
"#; "#;
let globals = gil.import("__main__").unwrap().dict().as_borrowed(); let globals = gil.import_bound("__main__").unwrap().dict();
globals globals
.set_item("cancellable_sleep", cancellable_sleep) .set_item("cancellable_sleep", cancellable_sleep)
.unwrap(); .unwrap();
@ -198,7 +198,7 @@ fn coroutine_is_cancelled() {
await task await task
asyncio.run(main()) asyncio.run(main())
"#; "#;
let globals = gil.import("__main__").unwrap().dict().as_borrowed(); let globals = gil.import_bound("__main__").unwrap().dict();
globals.set_item("sleep_loop", sleep_loop).unwrap(); globals.set_item("sleep_loop", sleep_loop).unwrap();
gil.run_bound( gil.run_bound(
&pyo3::unindent::unindent(&handle_windows(test)), &pyo3::unindent::unindent(&handle_windows(test)),

View File

@ -10,7 +10,7 @@ fn _get_subclasses<'py>(
args: &str, args: &str,
) -> PyResult<(Bound<'py, PyAny>, Bound<'py, PyAny>, Bound<'py, PyAny>)> { ) -> PyResult<(Bound<'py, PyAny>, Bound<'py, PyAny>, Bound<'py, PyAny>)> {
// Import the class from Python and create some subclasses // Import the class from Python and create some subclasses
let datetime = py.import("datetime")?; let datetime = py.import_bound("datetime")?;
let locals = [(py_type, datetime.getattr(py_type)?)].into_py_dict_bound(py); let locals = [(py_type, datetime.getattr(py_type)?)].into_py_dict_bound(py);

View File

@ -1,6 +1,6 @@
#![cfg(not(Py_LIMITED_API))] #![cfg(not(Py_LIMITED_API))]
use pyo3::{types::PyDate, Python}; use pyo3::{prelude::*, types::PyDate};
#[test] #[test]
#[should_panic(expected = "module 'datetime' has no attribute 'datetime_CAPI'")] #[should_panic(expected = "module 'datetime' has no attribute 'datetime_CAPI'")]
@ -14,7 +14,7 @@ fn test_bad_datetime_module_panic() {
std::fs::File::create(tmpdir.join("datetime.py")).unwrap(); std::fs::File::create(tmpdir.join("datetime.py")).unwrap();
Python::with_gil(|py: Python<'_>| { Python::with_gil(|py: Python<'_>| {
let sys = py.import("sys").unwrap(); let sys = py.import_bound("sys").unwrap();
sys.getattr("path") sys.getattr("path")
.unwrap() .unwrap()
.call_method1("insert", (0, tmpdir)) .call_method1("insert", (0, tmpdir))

View File

@ -134,7 +134,7 @@ impl PickleSupport {
} }
fn add_module(py: Python<'_>, module: &PyModule) -> PyResult<()> { fn add_module(py: Python<'_>, module: &PyModule) -> PyResult<()> {
py.import("sys")? py.import_bound("sys")?
.dict() .dict()
.get_item("modules") .get_item("modules")
.unwrap() .unwrap()

View File

@ -2,5 +2,5 @@ use pyo3::Python;
fn main() { fn main() {
let foo = if true { "foo" } else { "bar" }; let foo = if true { "foo" } else { "bar" };
Python::with_gil(|py| py.import(pyo3::intern!(py, foo)).unwrap()); Python::with_gil(|py| py.import_bound(pyo3::intern!(py, foo)).unwrap());
} }

View File

@ -1,7 +1,7 @@
error[E0435]: attempt to use a non-constant value in a constant error[E0435]: attempt to use a non-constant value in a constant
--> tests/ui/invalid_intern_arg.rs:5:55 --> tests/ui/invalid_intern_arg.rs:5:61
| |
5 | Python::with_gil(|py| py.import(pyo3::intern!(py, foo)).unwrap()); 5 | Python::with_gil(|py| py.import_bound(pyo3::intern!(py, foo)).unwrap());
| ------------------^^^- | ------------------^^^-
| | | | | |
| | non-constant value | | non-constant value