Skip to content

Commit

Permalink
Move from _bound suffixed APIs as part of PyO3 0.23 update (#1577)
Browse files Browse the repository at this point in the history
  • Loading branch information
davidhewitt authored Dec 12, 2024
1 parent 98bc1e2 commit d7650d1
Show file tree
Hide file tree
Showing 47 changed files with 142 additions and 154 deletions.
4 changes: 2 additions & 2 deletions src/build_tools.rs
Original file line number Diff line number Diff line change
Expand Up @@ -90,7 +90,7 @@ impl SchemaError {
ValidationError::new(line_errors, "Schema".to_object(py), InputType::Python, false);
let schema_error = SchemaError(SchemaErrorEnum::ValidationError(validation_error));
match Py::new(py, schema_error) {
Ok(err) => PyErr::from_value_bound(err.into_bound(py).into_any()),
Ok(err) => PyErr::from_value(err.into_bound(py).into_any()),
Err(err) => err,
}
}
Expand Down Expand Up @@ -124,7 +124,7 @@ impl SchemaError {

fn errors(&self, py: Python) -> PyResult<Py<PyList>> {
match &self.0 {
SchemaErrorEnum::Message(_) => Ok(PyList::empty_bound(py).unbind()),
SchemaErrorEnum::Message(_) => Ok(PyList::empty(py).unbind()),
SchemaErrorEnum::ValidationError(error) => error.errors(py, false, false, true),
}
}
Expand Down
6 changes: 3 additions & 3 deletions src/errors/location.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ use crate::lookup_key::{LookupPath, PathItem};

/// Used to store individual items of the error location, e.g. a string for key/field names
/// or a number for array indices.
#[derive(Clone, Eq, PartialEq)]
#[derive(Clone, Eq, PartialEq, IntoPyObjectRef)]
#[cfg_attr(debug_assertions, derive(Debug))]
pub enum LocItem {
/// string type key, used to identify items from a dict or anything that implements `__getitem__`
Expand Down Expand Up @@ -133,9 +133,9 @@ static EMPTY_TUPLE: GILOnceCell<PyObject> = GILOnceCell::new();
impl ToPyObject for Location {
fn to_object(&self, py: Python<'_>) -> PyObject {
match self {
Self::List(loc) => PyTuple::new_bound(py, loc.iter().rev()).to_object(py),
Self::List(loc) => PyTuple::new(py, loc.iter().rev()).unwrap().to_object(py),
Self::Empty => EMPTY_TUPLE
.get_or_init(py, || PyTuple::empty_bound(py).to_object(py))
.get_or_init(py, || PyTuple::empty(py).to_object(py))
.clone_ref(py),
}
}
Expand Down
2 changes: 1 addition & 1 deletion src/errors/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ pub use self::validation_exception::ValidationError;
pub use self::value_exception::{PydanticCustomError, PydanticKnownError, PydanticOmit, PydanticUseDefault};

pub fn py_err_string(py: Python, err: PyErr) -> String {
let value = err.value_bound(py);
let value = err.value(py);
match value.get_type().qualname() {
Ok(type_name) => match value.str() {
Ok(py_str) => {
Expand Down
6 changes: 3 additions & 3 deletions src/errors/types.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ pub fn list_all_errors(py: Python) -> PyResult<Bound<'_, PyList>> {
let mut errors: Vec<Bound<'_, PyDict>> = Vec::with_capacity(100);
for error_type in ErrorType::iter() {
if !matches!(error_type, ErrorType::CustomError { .. }) {
let d = PyDict::new_bound(py);
let d = PyDict::new(py);
d.set_item("type", error_type.to_string())?;
let message_template_python = error_type.message_template_python();
d.set_item("message_template_python", message_template_python)?;
Expand All @@ -39,7 +39,7 @@ pub fn list_all_errors(py: Python) -> PyResult<Bound<'_, PyList>> {
errors.push(d);
}
}
Ok(PyList::new_bound(py, errors))
PyList::new(py, errors)
}

fn field_from_context<'py, T: FromPyObject<'py>>(
Expand Down Expand Up @@ -745,7 +745,7 @@ impl ErrorType {
}

pub fn py_dict(&self, py: Python) -> PyResult<Option<Py<PyDict>>> {
let dict = PyDict::new_bound(py);
let dict = PyDict::new(py);
let custom_ctx_used = self.py_dict_update_ctx(py, &dict)?;

if let Self::CustomError { .. } = self {
Expand Down
22 changes: 11 additions & 11 deletions src/errors/validation_exception.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ use std::fmt::{Display, Write};
use std::str::from_utf8;

use pyo3::exceptions::{PyKeyError, PyTypeError, PyValueError};
use pyo3::ffi;
use pyo3::ffi::{self, c_str};
use pyo3::intern;
use pyo3::prelude::*;
use pyo3::sync::GILOnceCell;
Expand Down Expand Up @@ -73,7 +73,7 @@ impl ValidationError {
return cause_problem;
}
}
PyErr::from_value_bound(err.into_bound(py).into_any())
PyErr::from_value(err.into_bound(py).into_any())
}
Err(err) => err,
}
Expand Down Expand Up @@ -145,7 +145,7 @@ impl ValidationError {
use pyo3::exceptions::PyUserWarning;

let wrapped = PyUserWarning::new_err((note,));
wrapped.set_cause(py, Some(PyErr::from_value_bound(err.clone_ref(py).into_bound(py))));
wrapped.set_cause(py, Some(PyErr::from_value(err.clone_ref(py).into_bound(py))));
user_py_errs.push(wrapped);
}
}
Expand All @@ -167,7 +167,7 @@ impl ValidationError {
#[cfg(not(Py_3_11))]
let cause = {
use pyo3::exceptions::PyImportError;
match py.import_bound("exceptiongroup") {
match py.import("exceptiongroup") {
Ok(py_mod) => match py_mod.getattr("ExceptionGroup") {
Ok(group_cls) => match group_cls.call1((title, user_py_errs)) {
Ok(group_instance) => Some(group_instance.into_py(py)),
Expand Down Expand Up @@ -202,10 +202,10 @@ fn include_url_env(py: Python) -> bool {
match std::env::var_os("PYDANTIC_ERRORS_OMIT_URL") {
Some(val) => {
// We don't care whether warning succeeded or not, hence the assignment
let _ = PyErr::warn_bound(
let _ = PyErr::warn(
py,
&py.get_type_bound::<pyo3::exceptions::PyDeprecationWarning>(),
"PYDANTIC_ERRORS_OMIT_URL is deprecated, use PYDANTIC_ERRORS_INCLUDE_URL instead",
&py.get_type::<pyo3::exceptions::PyDeprecationWarning>(),
c_str!("PYDANTIC_ERRORS_OMIT_URL is deprecated, use PYDANTIC_ERRORS_INCLUDE_URL instead"),
1,
);
// If OMIT_URL exists but is empty, we include the URL:
Expand Down Expand Up @@ -298,7 +298,7 @@ impl ValidationError {
) -> PyResult<Py<PyList>> {
let url_prefix = get_url_prefix(py, include_url);
let mut iteration_error = None;
let list = PyList::new_bound(
let list = PyList::new(
py,
// PyList::new takes ExactSizeIterator, so if an error occurs during iteration we
// fill the list with None before returning the error; the list will then be thrown
Expand All @@ -313,7 +313,7 @@ impl ValidationError {
py.None()
})
}),
);
)?;
if let Some(err) = iteration_error {
Err(err)
} else {
Expand Down Expand Up @@ -368,7 +368,7 @@ impl ValidationError {
}
};
let s = from_utf8(&bytes).map_err(json_py_err)?;
Ok(PyString::new_bound(py, s))
Ok(PyString::new(py, s))
}

fn __repr__(&self, py: Python) -> String {
Expand Down Expand Up @@ -489,7 +489,7 @@ impl PyLineError {
input_type: InputType,
include_input: bool,
) -> PyResult<PyObject> {
let dict = PyDict::new_bound(py);
let dict = PyDict::new(py);
dict.set_item("type", self.error_type.type_string())?;
dict.set_item("loc", self.location.to_object(py))?;
dict.set_item("msg", self.error_type.render_message(py, input_type)?)?;
Expand Down
12 changes: 6 additions & 6 deletions src/input/datetime.rs
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,7 @@ impl EitherDate<'_> {
pub fn try_into_py(self, py: Python<'_>) -> PyResult<PyObject> {
let date = match self {
Self::Py(date) => Ok(date),
Self::Raw(date) => PyDate::new_bound(py, date.year.into(), date.month, date.day),
Self::Raw(date) => PyDate::new(py, date.year.into(), date.month, date.day),
}?;
Ok(date.into_py(py))
}
Expand Down Expand Up @@ -165,7 +165,7 @@ pub fn pytimedelta_subclass_as_duration(py_timedelta: &Bound<'_, PyDelta>) -> Py

pub fn duration_as_pytimedelta<'py>(py: Python<'py>, duration: &Duration) -> PyResult<Bound<'py, PyDelta>> {
let sign = if duration.positive { 1 } else { -1 };
PyDelta::new_bound(
PyDelta::new(
py,
sign * duration.day as i32,
sign * duration.second as i32,
Expand Down Expand Up @@ -211,7 +211,7 @@ impl EitherTime<'_> {
pub fn try_into_py(self, py: Python<'_>) -> PyResult<PyObject> {
let time = match self {
Self::Py(time) => Ok(time),
Self::Raw(time) => PyTime::new_bound(
Self::Raw(time) => PyTime::new(
py,
time.hour,
time.minute,
Expand Down Expand Up @@ -269,7 +269,7 @@ impl<'a> EitherDateTime<'a> {

pub fn try_into_py(self, py: Python<'a>) -> PyResult<PyObject> {
let dt = match self {
Self::Raw(datetime) => PyDateTime::new_bound(
Self::Raw(datetime) => PyDateTime::new(
py,
datetime.date.year.into(),
datetime.date.month,
Expand Down Expand Up @@ -393,7 +393,7 @@ pub fn float_as_datetime<'py>(input: &(impl Input<'py> + ?Sized), timestamp: f64

pub fn date_as_datetime<'py>(date: &Bound<'py, PyDate>) -> PyResult<EitherDateTime<'py>> {
let py = date.py();
let dt = PyDateTime::new_bound(
let dt = PyDateTime::new(
py,
date.getattr(intern!(py, "year"))?.extract()?,
date.getattr(intern!(py, "month"))?.extract()?,
Expand Down Expand Up @@ -518,7 +518,7 @@ impl TzInfo {

#[allow(unused_variables)]
fn utcoffset<'py>(&self, py: Python<'py>, dt: &Bound<'_, PyAny>) -> PyResult<Bound<'py, PyDelta>> {
PyDelta::new_bound(py, 0, self.seconds, 0, true)
PyDelta::new(py, 0, self.seconds, 0, true)
}

#[allow(unused_variables)]
Expand Down
6 changes: 3 additions & 3 deletions src/input/input_json.rs
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,7 @@ impl<'py, 'data> Input<'py> for JsonValue<'data> {
fn as_kwargs(&self, py: Python<'py>) -> Option<Bound<'py, PyDict>> {
match self {
JsonValue::Object(object) => {
let dict = PyDict::new_bound(py);
let dict = PyDict::new(py);
for (k, v) in LazyIndexMap::iter(object) {
dict.set_item(k, v.to_object(py)).unwrap();
}
Expand Down Expand Up @@ -171,7 +171,7 @@ impl<'py, 'data> Input<'py> for JsonValue<'data> {
fn validate_decimal(&self, _strict: bool, py: Python<'py>) -> ValMatch<Bound<'py, PyAny>> {
match self {
JsonValue::Float(f) => {
create_decimal(&PyString::new_bound(py, &f.to_string()), self).map(ValidationMatch::strict)
create_decimal(&PyString::new(py, &f.to_string()), self).map(ValidationMatch::strict)
}
JsonValue::Str(..) | JsonValue::Int(..) | JsonValue::BigInt(..) => {
create_decimal(self.to_object(py).bind(py), self).map(ValidationMatch::strict)
Expand Down Expand Up @@ -324,7 +324,7 @@ impl<'py, 'data> Input<'py> for JsonValue<'data> {
fn validate_complex(&self, strict: bool, py: Python<'py>) -> ValResult<ValidationMatch<EitherComplex<'py>>> {
match self {
JsonValue::Str(s) => Ok(ValidationMatch::strict(EitherComplex::Py(string_to_complex(
&PyString::new_bound(py, s),
&PyString::new(py, s),
self,
)?))),
JsonValue::Float(f) => {
Expand Down
8 changes: 3 additions & 5 deletions src/input/input_python.rs
Original file line number Diff line number Diff line change
Expand Up @@ -87,10 +87,8 @@ impl<'py> Input<'py> for Bound<'py, PyAny> {
Some(self)
}

fn as_kwargs(&self, py: Python<'py>) -> Option<Bound<'py, PyDict>> {
self.downcast::<PyDict>()
.ok()
.map(|dict| dict.to_owned().unbind().into_bound(py))
fn as_kwargs(&self, _py: Python<'py>) -> Option<Bound<'py, PyDict>> {
self.downcast::<PyDict>().ok().map(Bound::to_owned)
}

type Arguments<'a>
Expand Down Expand Up @@ -620,7 +618,7 @@ impl<'py> Input<'py> for Bound<'py, PyAny> {
if strict {
return Err(ValError::new(
ErrorType::IsInstanceOf {
class: PyComplex::type_object_bound(py)
class: PyComplex::type_object(py)
.qualname()
.and_then(|name| name.extract())
.unwrap_or_else(|_| "complex".to_owned()),
Expand Down
4 changes: 2 additions & 2 deletions src/input/return_enums.rs
Original file line number Diff line number Diff line change
Expand Up @@ -548,7 +548,7 @@ impl EitherBytes<'_, '_> {
impl IntoPy<PyObject> for EitherBytes<'_, '_> {
fn into_py(self, py: Python<'_>) -> PyObject {
match self {
EitherBytes::Cow(bytes) => PyBytes::new_bound(py, &bytes).into_py(py),
EitherBytes::Cow(bytes) => PyBytes::new(py, &bytes).into_py(py),
EitherBytes::Py(py_bytes) => py_bytes.into_py(py),
}
}
Expand Down Expand Up @@ -755,7 +755,7 @@ pub enum EitherComplex<'a> {
impl IntoPy<PyObject> for EitherComplex<'_> {
fn into_py(self, py: Python<'_>) -> PyObject {
match self {
Self::Complex(c) => PyComplex::from_doubles_bound(py, c[0], c[1]).into_py(py),
Self::Complex(c) => PyComplex::from_doubles(py, c[0], c[1]).into_py(py),
Self::Py(c) => c.into_py(py),
}
}
Expand Down
2 changes: 1 addition & 1 deletion src/input/shared.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ static ENUM_META_OBJECT: GILOnceCell<Py<PyAny>> = GILOnceCell::new();
pub fn get_enum_meta_object(py: Python) -> &Bound<'_, PyAny> {
ENUM_META_OBJECT
.get_or_init(py, || {
py.import_bound(intern!(py, "enum"))
py.import(intern!(py, "enum"))
.and_then(|enum_module| enum_module.getattr(intern!(py, "EnumMeta")))
.unwrap()
.into()
Expand Down
2 changes: 1 addition & 1 deletion src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -89,7 +89,7 @@ fn get_pydantic_version(py: Python<'_>) -> Option<&'static str> {

PYDANTIC_VERSION
.get_or_init(py, || {
py.import_bound("pydantic")
py.import("pydantic")
.and_then(|pydantic| pydantic.getattr("__version__")?.extract())
.ok()
})
Expand Down
8 changes: 4 additions & 4 deletions src/lookup_key.rs
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,7 @@ impl LookupKey {
py_key1: alias_py.clone().into(),
path1,
key2: alt_alias.to_string(),
py_key2: PyString::new_bound(py, alt_alias).into(),
py_key2: PyString::new(py, alt_alias).into(),
path2: LookupPath::from_str(py, alt_alias, None),
}),
None => Ok(Self::simple(py, &alias, Some(alias_py.clone()))),
Expand Down Expand Up @@ -97,7 +97,7 @@ impl LookupKey {
fn simple(py: Python, key: &str, opt_py_key: Option<Bound<'_, PyString>>) -> Self {
let py_key = match &opt_py_key {
Some(py_key) => py_key.clone(),
None => PyString::new_bound(py, key),
None => PyString::new(py, key),
};
Self::Simple {
key: key.to_string(),
Expand Down Expand Up @@ -346,7 +346,7 @@ impl LookupPath {
fn from_str(py: Python, key: &str, py_key: Option<Bound<'_, PyString>>) -> Self {
let py_key = match py_key {
Some(py_key) => py_key,
None => PyString::new_bound(py, key),
None => PyString::new(py, key),
};
Self(vec![PathItem::S(key.to_string(), py_key.into())])
}
Expand Down Expand Up @@ -511,7 +511,7 @@ fn py_get_attrs<'py>(obj: &Bound<'py, PyAny>, attr_name: &Py<PyString>) -> PyRes
match obj.getattr(attr_name) {
Ok(attr) => Ok(Some(attr)),
Err(err) => {
if err.get_type_bound(obj.py()).is_subclass_of::<PyAttributeError>()? {
if err.get_type(obj.py()).is_subclass_of::<PyAttributeError>()? {
Ok(None)
} else {
Err(err)
Expand Down
4 changes: 2 additions & 2 deletions src/serializers/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -189,8 +189,8 @@ impl BytesMode {
}

pub fn utf8_py_error(py: Python, err: Utf8Error, data: &[u8]) -> PyErr {
match pyo3::exceptions::PyUnicodeDecodeError::new_utf8_bound(py, data, err) {
Ok(decode_err) => PyErr::from_value_bound(decode_err.into_any()),
match pyo3::exceptions::PyUnicodeDecodeError::new_utf8(py, data, err) {
Ok(decode_err) => PyErr::from_value(decode_err.into_any()),
Err(err) => err,
}
}
Expand Down
7 changes: 4 additions & 3 deletions src/serializers/extra.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
use std::ffi::CString;
use std::fmt;
use std::sync::Mutex;

Expand Down Expand Up @@ -408,7 +409,7 @@ impl CollectWarnings {
let type_name = value
.get_type()
.qualname()
.unwrap_or_else(|_| PyString::new_bound(value.py(), "<unknown python object>"));
.unwrap_or_else(|_| PyString::new(value.py(), "<unknown python object>"));

let value_str = truncate_safe_repr(value, None);
Err(PydanticSerializationUnexpectedValue::new_err(Some(format!(
Expand Down Expand Up @@ -445,7 +446,7 @@ impl CollectWarnings {
let type_name = value
.get_type()
.qualname()
.unwrap_or_else(|_| PyString::new_bound(value.py(), "<unknown python object>"));
.unwrap_or_else(|_| PyString::new(value.py(), "<unknown python object>"));

let value_str = truncate_safe_repr(value, None);

Expand All @@ -472,7 +473,7 @@ impl CollectWarnings {
let message = format!("Pydantic serializer warnings:\n {}", warnings.join("\n "));
if self.mode == WarningsMode::Warn {
let user_warning_type = PyUserWarning::type_object(py);
PyErr::warn_bound(py, &user_warning_type, &message, 0)
PyErr::warn(py, &user_warning_type, &CString::new(message)?, 0)
} else {
Err(PydanticSerializationError::new_err(message))
}
Expand Down
6 changes: 2 additions & 4 deletions src/serializers/fields.rs
Original file line number Diff line number Diff line change
Expand Up @@ -41,9 +41,7 @@ impl SerField {
serializer: Option<CombinedSerializer>,
required: bool,
) -> Self {
let alias_py = alias
.as_ref()
.map(|alias| PyString::new_bound(py, alias.as_str()).into());
let alias_py = alias.as_ref().map(|alias| PyString::new(py, alias.as_str()).into());
Self {
key_py,
alias,
Expand Down Expand Up @@ -153,7 +151,7 @@ impl GeneralFieldsSerializer {
exclude: Option<&Bound<'py, PyAny>>,
extra: Extra,
) -> PyResult<Bound<'py, PyDict>> {
let output_dict = PyDict::new_bound(py);
let output_dict = PyDict::new(py);
let mut used_req_fields: usize = 0;

// NOTE! we maintain the order of the input dict assuming that's right
Expand Down
Loading

0 comments on commit d7650d1

Please sign in to comment.