Skip to content

Commit f081d3e

Browse files
committed
disable gil-refs feature
1 parent 2403e50 commit f081d3e

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

41 files changed

+150
-153
lines changed

Cargo.toml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -27,7 +27,7 @@ include = [
2727
rust-version = "1.70"
2828

2929
[dependencies]
30-
pyo3 = { version = "0.21.0-beta.0", features = ["generate-import-lib", "num-bigint", "gil-refs"] }
30+
pyo3 = { version = "0.21.0-beta.0", features = ["generate-import-lib", "num-bigint"] }
3131
regex = "1.10.3"
3232
strum = { version = "0.25.0", features = ["derive"] }
3333
strum_macros = "0.26.1"

src/argument_markers.rs

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -15,9 +15,9 @@ pub struct ArgsKwargs {
1515

1616
impl ArgsKwargs {
1717
fn eq(&self, py: Python, other: &Self) -> PyResult<bool> {
18-
if self.args.as_ref(py).eq(other.args.as_ref(py))? {
18+
if self.args.bind(py).eq(other.args.bind(py))? {
1919
match (&self.kwargs, &other.kwargs) {
20-
(Some(d1), Some(d2)) => d1.as_ref(py).eq(d2.as_ref(py)),
20+
(Some(d1), Some(d2)) => d1.bind(py).eq(d2.bind(py)),
2121
(None, None) => Ok(true),
2222
_ => Ok(false),
2323
}
@@ -50,7 +50,7 @@ impl ArgsKwargs {
5050
Ok(b) => (!b).into_py(py),
5151
Err(e) => e.into_py(py),
5252
},
53-
_ => py.NotImplemented().into(),
53+
_ => py.NotImplemented(),
5454
}
5555
}
5656

src/build_tools.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -90,7 +90,7 @@ impl SchemaError {
9090
ValidationError::new(line_errors, "Schema".to_object(py), InputType::Python, false);
9191
let schema_error = SchemaError(SchemaErrorEnum::ValidationError(validation_error));
9292
match Py::new(py, schema_error) {
93-
Ok(err) => PyErr::from_value(err.as_ref(py)),
93+
Ok(err) => PyErr::from_value_bound(err.into_bound(py).into_any()),
9494
Err(err) => err,
9595
}
9696
}

src/errors/mod.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,7 @@ pub use self::validation_exception::ValidationError;
1313
pub use self::value_exception::{PydanticCustomError, PydanticKnownError, PydanticOmit, PydanticUseDefault};
1414

1515
pub fn py_err_string(py: Python, err: PyErr) -> String {
16-
let value = err.value(py);
16+
let value = err.value_bound(py);
1717
match value.get_type().qualname() {
1818
Ok(type_name) => match value.str() {
1919
Ok(py_str) => {

src/errors/types.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -670,13 +670,13 @@ impl ErrorType {
670670
Self::ValueError { error, .. } => {
671671
let error = &error
672672
.as_ref()
673-
.map_or(Cow::Borrowed("None"), |v| Cow::Owned(v.as_ref(py).to_string()));
673+
.map_or(Cow::Borrowed("None"), |v| Cow::Owned(v.bind(py).to_string()));
674674
render!(tmpl, error)
675675
}
676676
Self::AssertionError { error, .. } => {
677677
let error = &error
678678
.as_ref()
679-
.map_or(Cow::Borrowed("None"), |v| Cow::Owned(v.as_ref(py).to_string()));
679+
.map_or(Cow::Borrowed("None"), |v| Cow::Owned(v.bind(py).to_string()));
680680
render!(tmpl, error)
681681
}
682682
Self::CustomError {

src/errors/validation_exception.rs

Lines changed: 8 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -73,7 +73,7 @@ impl ValidationError {
7373
return cause_problem;
7474
}
7575
}
76-
PyErr::from_value(err.as_ref(py))
76+
PyErr::from_value_bound(err.into_bound(py).into_any())
7777
}
7878
Err(err) => err,
7979
}
@@ -202,9 +202,9 @@ fn include_url_env(py: Python) -> bool {
202202
match std::env::var_os("PYDANTIC_ERRORS_OMIT_URL") {
203203
Some(val) => {
204204
// We don't care whether warning succeeded or not, hence the assignment
205-
let _ = PyErr::warn(
205+
let _ = PyErr::warn_bound(
206206
py,
207-
py.get_type::<pyo3::exceptions::PyDeprecationWarning>(),
207+
&py.get_type_bound::<pyo3::exceptions::PyDeprecationWarning>(),
208208
"PYDANTIC_ERRORS_OMIT_URL is deprecated, use PYDANTIC_ERRORS_INCLUDE_URL instead",
209209
1,
210210
);
@@ -297,12 +297,12 @@ impl ValidationError {
297297
// away safely.
298298
self.line_errors.iter().map(|e| -> PyObject {
299299
if iteration_error.is_some() {
300-
return py.None().into();
300+
return py.None();
301301
}
302302
e.as_dict(py, url_prefix, include_context, self.input_type, include_input)
303303
.unwrap_or_else(|err| {
304304
iteration_error = Some(err);
305-
py.None().into()
305+
py.None()
306306
})
307307
}),
308308
);
@@ -361,12 +361,12 @@ impl ValidationError {
361361
self.__repr__(py)
362362
}
363363

364-
fn __reduce__(slf: &PyCell<Self>) -> PyResult<(&PyAny, PyObject)> {
364+
fn __reduce__<'py>(slf: &Bound<'py, Self>) -> PyResult<(Bound<'py, PyAny>, PyObject)> {
365365
let py = slf.py();
366366
let callable = slf.getattr("from_exception_data")?;
367367
let borrow = slf.try_borrow()?;
368368
let args = (
369-
borrow.title.as_ref(py),
369+
borrow.title.bind(py),
370370
borrow.errors(py, include_url_env(py), true, true)?,
371371
borrow.input_type.into_py(py),
372372
borrow.hide_input,
@@ -492,7 +492,7 @@ impl TryFrom<&Bound<'_, PyAny>> for PyLineError {
492492

493493
let input_value = match dict.get_item("input")? {
494494
Some(i) => i.into_py(py),
495-
None => py.None().into(),
495+
None => py.None(),
496496
};
497497

498498
Ok(Self {

src/errors/value_exception.rs

Lines changed: 2 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -99,7 +99,7 @@ impl PydanticCustomError {
9999
fn __repr__(&self, py: Python) -> PyResult<String> {
100100
let msg = self.message(py)?;
101101
match self.context.as_ref() {
102-
Some(ctx) => Ok(format!("{msg} [type={}, context={}]", self.error_type, ctx.as_ref(py))),
102+
Some(ctx) => Ok(format!("{msg} [type={}, context={}]", self.error_type, ctx.bind(py))),
103103
None => Ok(format!("{msg} [type={}, context=None]", self.error_type)),
104104
}
105105
}
@@ -174,11 +174,7 @@ impl PydanticKnownError {
174174
fn __repr__(&self, py: Python) -> PyResult<String> {
175175
let msg = self.message(py)?;
176176
match self.context(py)?.as_ref() {
177-
Some(ctx) => Ok(format!(
178-
"{msg} [type={}, context={}]",
179-
self.error_type(),
180-
ctx.as_ref(py)
181-
)),
177+
Some(ctx) => Ok(format!("{msg} [type={}, context={}]", self.error_type(), ctx.bind(py))),
182178
None => Ok(format!("{msg} [type={}, context=None]", self.error_type())),
183179
}
184180
}

src/input/return_enums.rs

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,7 @@ use pyo3::types::{
1414
PyByteArray, PyBytes, PyDict, PyFloat, PyFrozenSet, PyIterator, PyList, PyMapping, PySequence, PySet, PyString,
1515
PyTuple,
1616
};
17-
use pyo3::{ffi, intern, PyNativeType};
17+
use pyo3::{ffi, intern};
1818

1919
#[cfg(not(PyPy))]
2020
use pyo3::types::PyFunction;
@@ -213,7 +213,7 @@ pub trait BuildSet {
213213
fn build_len(&self) -> usize;
214214
}
215215

216-
impl BuildSet for &PySet {
216+
impl BuildSet for Bound<'_, PySet> {
217217
fn build_add(&self, item: PyObject) -> PyResult<()> {
218218
self.add(item)
219219
}
@@ -223,7 +223,7 @@ impl BuildSet for &PySet {
223223
}
224224
}
225225

226-
impl BuildSet for &PyFrozenSet {
226+
impl BuildSet for Bound<'_, PyFrozenSet> {
227227
fn build_add(&self, item: PyObject) -> PyResult<()> {
228228
py_error_on_minusone(self.py(), unsafe {
229229
// Safety: self.as_ptr() the _only_ pointer to the `frozenset`, and it's allowed
@@ -240,7 +240,7 @@ impl BuildSet for &PyFrozenSet {
240240
#[allow(clippy::too_many_arguments)]
241241
fn validate_iter_to_set<'a, 's>(
242242
py: Python<'a>,
243-
set: impl BuildSet,
243+
set: &impl BuildSet,
244244
iter: impl Iterator<Item = PyResult<impl BorrowInput>>,
245245
input: &'a (impl Input<'a> + 'a),
246246
field_type: &'static str,
@@ -363,7 +363,7 @@ impl<'a> GenericIterable<'a> {
363363
pub fn validate_to_set<'s>(
364364
&'s self,
365365
py: Python<'a>,
366-
set: impl BuildSet,
366+
set: &impl BuildSet,
367367
input: &'a impl Input<'a>,
368368
max_length: Option<usize>,
369369
field_type: &'static str,

src/lib.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -73,7 +73,7 @@ fn get_pydantic_version(py: Python<'_>) -> Option<&'static str> {
7373

7474
PYDANTIC_VERSION
7575
.get_or_init(py, || {
76-
py.import("pydantic")
76+
py.import_bound("pydantic")
7777
.and_then(|pydantic| pydantic.getattr("__version__")?.extract())
7878
.ok()
7979
})
@@ -89,7 +89,7 @@ pub fn build_info() -> String {
8989
}
9090

9191
#[pymodule]
92-
fn _pydantic_core(py: Python, m: &PyModule) -> PyResult<()> {
92+
fn _pydantic_core(py: Python, m: &Bound<'_, PyModule>) -> PyResult<()> {
9393
m.add("__version__", get_pydantic_core_version())?;
9494
m.add("build_profile", env!("PROFILE"))?;
9595
m.add("build_info", build_info())?;

src/lookup_key.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -507,7 +507,7 @@ fn py_get_attrs<'py>(obj: &Bound<'py, PyAny>, attr_name: &Py<PyString>) -> PyRes
507507
match obj.getattr(attr_name.extract::<&PyString>(obj.py())?) {
508508
Ok(attr) => Ok(Some(attr)),
509509
Err(err) => {
510-
if err.get_type(obj.py()).is_subclass_of::<PyAttributeError>()? {
510+
if err.get_type_bound(obj.py()).is_subclass_of::<PyAttributeError>()? {
511511
Ok(None)
512512
} else {
513513
Err(err)

src/serializers/computed_fields.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -184,7 +184,7 @@ impl_py_gc_traverse!(ComputedFieldSerializer<'_> { computed_field });
184184
impl<'py> Serialize for ComputedFieldSerializer<'py> {
185185
fn serialize<S: serde::ser::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
186186
let py = self.model.py();
187-
let property_name_py = self.computed_field.property_name_py.as_ref(py);
187+
let property_name_py = self.computed_field.property_name_py.bind(py);
188188
let next_value = self.model.getattr(property_name_py).map_err(py_err_se_err)?;
189189
let s = PydanticSerializer::new(
190190
&next_value,

src/serializers/config.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -190,8 +190,8 @@ impl BytesMode {
190190
}
191191

192192
pub fn utf8_py_error(py: Python, err: Utf8Error, data: &[u8]) -> PyErr {
193-
match pyo3::exceptions::PyUnicodeDecodeError::new_utf8(py, data, err) {
194-
Ok(decode_err) => PyErr::from_value(decode_err),
193+
match pyo3::exceptions::PyUnicodeDecodeError::new_utf8_bound(py, data, err) {
194+
Ok(decode_err) => PyErr::from_value_bound(decode_err.into_any()),
195195
Err(err) => err,
196196
}
197197
}

src/serializers/extra.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -358,8 +358,8 @@ impl CollectWarnings {
358358
match *self.warnings.borrow() {
359359
Some(ref warnings) => {
360360
let message = format!("Pydantic serializer warnings:\n {}", warnings.join("\n "));
361-
let user_warning_type = py.import("builtins")?.getattr("UserWarning")?;
362-
PyErr::warn(py, user_warning_type, &message, 0)
361+
let user_warning_type = py.import_bound("builtins")?.getattr("UserWarning")?;
362+
PyErr::warn_bound(py, &user_warning_type, &message, 0)
363363
}
364364
_ => Ok(()),
365365
}

src/serializers/infer.rs

Lines changed: 6 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ use std::borrow::Cow;
33
use pyo3::exceptions::PyTypeError;
44
use pyo3::intern;
55
use pyo3::prelude::*;
6+
use pyo3::pybacked::PyBackedStr;
67
use pyo3::types::{PyByteArray, PyBytes, PyDict, PyFrozenSet, PyIterator, PyList, PySet, PyString, PyTuple};
78

89
use serde::ser::{Error, Serialize, SerializeMap, SerializeSeq, Serializer};
@@ -510,18 +511,18 @@ pub(crate) fn infer_serialize_known<S: Serializer>(
510511
seq.end()
511512
}
512513
ObType::Path => {
513-
let s = value
514+
let s: PyBackedStr = value
514515
.str()
515516
.and_then(|value_str| value_str.extract())
516517
.map_err(py_err_se_err)?;
517-
serializer.serialize_str(s)
518+
serializer.serialize_str(&s)
518519
}
519520
ObType::Pattern => {
520-
let s = value
521+
let s: PyBackedStr = value
521522
.getattr(intern!(value.py(), "pattern"))
522523
.and_then(|pattern| pattern.str()?.extract())
523524
.map_err(py_err_se_err)?;
524-
serializer.serialize_str(s)
525+
serializer.serialize_str(&s)
525526
}
526527
ObType::Unknown => {
527528
if let Some(fallback) = extra.fallback {
@@ -678,7 +679,7 @@ fn serialize_pairs_python<'py>(
678679
extra: &Extra,
679680
key_transform: impl Fn(Bound<'py, PyAny>) -> PyResult<Bound<'py, PyAny>>,
680681
) -> PyResult<PyObject> {
681-
let new_dict = PyDict::new(py);
682+
let new_dict = PyDict::new_bound(py);
682683
let filter = AnyFilter::new();
683684

684685
for result in pairs_iter {

src/serializers/mod.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -189,7 +189,7 @@ impl SchemaSerializer {
189189
Ok(py_bytes.into())
190190
}
191191

192-
pub fn __reduce__(slf: &PyCell<Self>) -> PyResult<(PyObject, (PyObject, PyObject))> {
192+
pub fn __reduce__(slf: &Bound<Self>) -> PyResult<(PyObject, (PyObject, PyObject))> {
193193
// Enables support for `pickle` serialization.
194194
let py = slf.py();
195195
let cls = slf.get_type().into();

src/serializers/ob_type.rs

Lines changed: 18 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -68,7 +68,12 @@ impl ObTypeLookup {
6868
float: PyFloat::type_object_raw(py) as usize,
6969
list: PyList::type_object_raw(py) as usize,
7070
dict: PyDict::type_object_raw(py) as usize,
71-
decimal_object: py.import("decimal").unwrap().getattr("Decimal").unwrap().to_object(py),
71+
decimal_object: py
72+
.import_bound("decimal")
73+
.unwrap()
74+
.getattr("Decimal")
75+
.unwrap()
76+
.to_object(py),
7277
string: PyString::type_object_raw(py) as usize,
7378
bytes: PyBytes::type_object_raw(py) as usize,
7479
bytearray: PyByteArray::type_object_raw(py) as usize,
@@ -81,16 +86,21 @@ impl ObTypeLookup {
8186
timedelta: PyDelta::type_object_raw(py) as usize,
8287
url: PyUrl::type_object_raw(py) as usize,
8388
multi_host_url: PyMultiHostUrl::type_object_raw(py) as usize,
84-
enum_object: py.import("enum").unwrap().getattr("Enum").unwrap().to_object(py),
89+
enum_object: py.import_bound("enum").unwrap().getattr("Enum").unwrap().to_object(py),
8590
generator_object: py
86-
.import("types")
91+
.import_bound("types")
8792
.unwrap()
8893
.getattr("GeneratorType")
8994
.unwrap()
9095
.to_object(py),
91-
path_object: py.import("pathlib").unwrap().getattr("Path").unwrap().to_object(py),
92-
pattern_object: py.import("re").unwrap().getattr("Pattern").unwrap().to_object(py),
93-
uuid_object: py.import("uuid").unwrap().getattr("UUID").unwrap().to_object(py),
96+
path_object: py
97+
.import_bound("pathlib")
98+
.unwrap()
99+
.getattr("Path")
100+
.unwrap()
101+
.to_object(py),
102+
pattern_object: py.import_bound("re").unwrap().getattr("Pattern").unwrap().to_object(py),
103+
uuid_object: py.import_bound("uuid").unwrap().getattr("UUID").unwrap().to_object(py),
94104
}
95105
}
96106

@@ -267,9 +277,9 @@ impl ObTypeLookup {
267277
fn is_enum(&self, op_value: Option<&Bound<'_, PyAny>>, py_type: &Bound<'_, PyType>) -> bool {
268278
// only test on the type itself, not base types
269279
if op_value.is_some() {
270-
let enum_meta_type = self.enum_object.as_ref(py_type.py()).get_type();
280+
let enum_meta_type = self.enum_object.bind(py_type.py()).get_type();
271281
let meta_type = py_type.get_type();
272-
meta_type.is(enum_meta_type)
282+
meta_type.is(&enum_meta_type)
273283
} else {
274284
false
275285
}

src/serializers/shared.rs

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -381,7 +381,7 @@ where
381381

382382
let next = move |(field_name, field): (Bound<'py, PyAny>, Bound<'py, PyAny>)| -> PyResult<Option<(Bound<'py, PyAny>, Bound<'py, PyAny>)>> {
383383
let field_type = field.getattr(intern!(py, "_field_type"))?;
384-
if field_type.is(field_type_marker) {
384+
if field_type.is(&field_type_marker) {
385385
let value = dataclass.getattr(field_name.downcast::<PyString>()?)?;
386386
Ok(Some((field_name, value)))
387387
} else {
@@ -395,9 +395,9 @@ where
395395
static DC_FIELD_MARKER: GILOnceCell<PyObject> = GILOnceCell::new();
396396

397397
/// needed to match the logic from dataclasses.fields `tuple(f for f in fields.values() if f._field_type is _FIELD)`
398-
fn get_field_marker(py: Python<'_>) -> PyResult<&PyAny> {
398+
fn get_field_marker(py: Python<'_>) -> PyResult<Bound<'_, PyAny>> {
399399
let field_type_marker_obj = DC_FIELD_MARKER.get_or_try_init(py, || {
400-
py.import("dataclasses")?.getattr("_FIELD").map(|f| f.into_py(py))
400+
py.import_bound("dataclasses")?.getattr("_FIELD").map(|f| f.into_py(py))
401401
})?;
402-
Ok(field_type_marker_obj.as_ref(py))
402+
Ok(field_type_marker_obj.bind(py).clone())
403403
}

src/serializers/type_serializers/dataclass.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -115,7 +115,7 @@ impl DataclassSerializer {
115115
let dict = PyDict::new_bound(py);
116116

117117
for field_name in &self.fields {
118-
let field_name = field_name.as_ref(py);
118+
let field_name = field_name.bind(py);
119119
dict.set_item(field_name, value.getattr(field_name)?)?;
120120
}
121121
Ok(dict)

0 commit comments

Comments
 (0)