Skip to content

Commit 8d08c3d

Browse files
committed
cleanups for type name change
1 parent 9394424 commit 8d08c3d

File tree

16 files changed

+105
-232
lines changed

16 files changed

+105
-232
lines changed

benches/main.rs

Lines changed: 59 additions & 193 deletions
Large diffs are not rendered by default.

src/argument_markers.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -55,9 +55,9 @@ impl ArgsKwargs {
5555
}
5656

5757
pub fn __repr__(&self, py: Python) -> String {
58-
let args = safe_repr(self.args.as_ref(py));
58+
let args = safe_repr(self.args.attach(py));
5959
match self.kwargs {
60-
Some(ref d) => format!("ArgsKwargs({args}, {})", safe_repr(d.as_ref(py))),
60+
Some(ref d) => format!("ArgsKwargs({args}, {})", safe_repr(d.attach(py))),
6161
None => format!("ArgsKwargs({args})"),
6262
}
6363
}

src/errors/types.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -782,7 +782,7 @@ impl From<Int> for Number {
782782

783783
impl FromPyObject<'_> for Number {
784784
fn extract(obj: &PyAny) -> PyResult<Self> {
785-
if let Ok(int) = extract_i64(obj) {
785+
if let Ok(int) = extract_i64(Py2::borrowed_from_gil_ref(&obj)) {
786786
Ok(Number::Int(int))
787787
} else if let Ok(float) = obj.extract::<f64>() {
788788
Ok(Number::Float(float))

src/errors/validation_exception.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -528,7 +528,7 @@ impl PyLineError {
528528
write!(output, " {message} [type={}", self.error_type.type_string())?;
529529

530530
if !hide_input {
531-
let input_value = self.input_value.as_ref(py);
531+
let input_value = self.input_value.attach(py);
532532
let input_str = safe_repr(input_value);
533533
truncate_input_value!(output, &input_str);
534534

src/errors/value_exception.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -122,7 +122,7 @@ impl PydanticCustomError {
122122
let key: &PyString = key.downcast()?;
123123
if let Ok(py_str) = value.downcast::<PyString>() {
124124
message = message.replace(&format!("{{{}}}", key.to_str()?), py_str.to_str()?);
125-
} else if let Ok(value_int) = extract_i64(value) {
125+
} else if let Ok(value_int) = extract_i64(Py2::borrowed_from_gil_ref(&value)) {
126126
message = message.replace(&format!("{{{}}}", key.to_str()?), &value_int.to_string());
127127
} else {
128128
// fallback for anything else just in case

src/input/input_python.rs

Lines changed: 10 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -274,7 +274,7 @@ impl<'a> Input<'a> for Py2<'a, PyAny> {
274274
if !strict {
275275
if let Some(cow_str) = maybe_as_string(self, ErrorTypeDefaults::BoolParsing)? {
276276
return str_as_bool(self, &cow_str).map(ValidationMatch::lax);
277-
} else if let Ok(int) = extract_i64(self.as_gil_ref()) {
277+
} else if let Ok(int) = extract_i64(self) {
278278
return int_as_bool(self, int).map(ValidationMatch::lax);
279279
} else if let Ok(float) = self.extract::<f64>() {
280280
if let Ok(int) = float_as_int(self, float) {
@@ -370,7 +370,10 @@ impl<'a> Input<'a> for Py2<'a, PyAny> {
370370

371371
Err(ValError::new(
372372
ErrorType::IsInstanceOf {
373-
class: decimal_type.name().unwrap_or("Decimal").to_string(),
373+
class: decimal_type
374+
.name()
375+
.and_then(|any| any.extract())
376+
.unwrap_or_else(|_| "Decimal".into()),
374377
context: None,
375378
},
376379
self,
@@ -618,7 +621,7 @@ impl<'a> Input<'a> for Py2<'a, PyAny> {
618621
bytes_as_time(self, py_bytes.as_bytes(), microseconds_overflow_behavior)
619622
} else if PyBool::is_exact_type_of(self.as_gil_ref()) {
620623
Err(ValError::new(ErrorTypeDefaults::TimeType, self))
621-
} else if let Ok(int) = extract_i64(self.as_gil_ref()) {
624+
} else if let Ok(int) = extract_i64(self) {
622625
int_as_time(self, int, 0)
623626
} else if let Ok(float) = self.extract::<f64>() {
624627
float_as_time(self, float)
@@ -652,7 +655,7 @@ impl<'a> Input<'a> for Py2<'a, PyAny> {
652655
bytes_as_datetime(self, py_bytes.as_bytes(), microseconds_overflow_behavior)
653656
} else if PyBool::is_exact_type_of(self.as_gil_ref()) {
654657
Err(ValError::new(ErrorTypeDefaults::DatetimeType, self))
655-
} else if let Ok(int) = extract_i64(self.as_gil_ref()) {
658+
} else if let Ok(int) = extract_i64(self) {
656659
int_as_datetime(self, int, 0)
657660
} else if let Ok(float) = self.extract::<f64>() {
658661
float_as_datetime(self, float)
@@ -689,7 +692,7 @@ impl<'a> Input<'a> for Py2<'a, PyAny> {
689692
bytes_as_timedelta(self, str.as_bytes(), microseconds_overflow_behavior)
690693
} else if let Ok(py_bytes) = self.downcast::<PyBytes>() {
691694
bytes_as_timedelta(self, py_bytes.as_bytes(), microseconds_overflow_behavior)
692-
} else if let Ok(int) = extract_i64(self.as_gil_ref()) {
695+
} else if let Ok(int) = extract_i64(self) {
693696
Ok(int_as_duration(self, int)?.into())
694697
} else if let Ok(float) = self.extract::<f64>() {
695698
Ok(float_as_duration(self, float)?.into())
@@ -708,10 +711,10 @@ impl AsLocItem for Py2<'_, PyAny> {
708711
fn as_loc_item(&self) -> LocItem {
709712
if let Ok(py_str) = self.downcast::<PyString>() {
710713
py_str.to_string_lossy().as_ref().into()
711-
} else if let Ok(key_int) = extract_i64(self.as_gil_ref()) {
714+
} else if let Ok(key_int) = extract_i64(self) {
712715
key_int.into()
713716
} else {
714-
safe_repr(self.as_gil_ref()).to_string().into()
717+
safe_repr(self).into_owned().into()
715718
}
716719
}
717720
}

src/input/input_string.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -56,7 +56,7 @@ impl AsLocItem for StringMapping<'_> {
5656
fn as_loc_item(&self) -> LocItem {
5757
match self {
5858
Self::String(s) => s.to_string_lossy().as_ref().into(),
59-
Self::Mapping(d) => safe_repr(d.as_gil_ref()).to_string().into(),
59+
Self::Mapping(d) => safe_repr(d).into_owned().into(),
6060
}
6161
}
6262
}

src/lookup_key.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -431,7 +431,7 @@ impl PathItem {
431431
} else {
432432
Ok(Self::Pos(usize_key))
433433
}
434-
} else if let Ok(int_key) = extract_i64(obj.as_gil_ref()) {
434+
} else if let Ok(int_key) = extract_i64(obj) {
435435
if index == 0 {
436436
py_err!(PyTypeError; "The first item in an alias path should be a string")
437437
} else {

src/serializers/infer.rs

Lines changed: 4 additions & 3 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::types::PyType;
67
use pyo3::types::{
78
PyByteArray, PyBytes, PyDate, PyDateTime, PyDict, PyFrozenSet, PyIterator, PyList, PySet, PyString, PyTime, PyTuple,
89
};
@@ -122,7 +123,7 @@ pub(crate) fn infer_to_python_known(
122123
// `bool` and `None` can't be subclasses, `ObType::Int`, `ObType::Float`, `ObType::Str` refer to exact types
123124
ObType::None | ObType::Bool | ObType::Int | ObType::Float | ObType::Str => value.into_py(py),
124125
// have to do this to make sure subclasses of for example str are upcast to `str`
125-
ObType::IntSubclass => extract_i64(value)?.into_py(py),
126+
ObType::IntSubclass => extract_i64(Py2::borrowed_from_gil_ref(&value))?.into_py(py),
126127
ObType::FloatSubclass => value.extract::<f64>()?.into_py(py),
127128
ObType::Decimal => value.to_string().into_py(py),
128129
ObType::StrSubclass => value.extract::<&str>()?.into_py(py),
@@ -543,7 +544,7 @@ pub(crate) fn infer_serialize_known<S: Serializer>(
543544
let msg = format!(
544545
"{}Unable to serialize unknown type: {}",
545546
SERIALIZATION_ERR_MARKER,
546-
safe_repr(value.get_type()),
547+
safe_repr(Py2::<PyType>::borrowed_from_gil_ref(&value.get_type())),
547548
);
548549
return Err(S::Error::custom(msg));
549550
}
@@ -556,7 +557,7 @@ pub(crate) fn infer_serialize_known<S: Serializer>(
556557
fn unknown_type_error(value: &PyAny) -> PyErr {
557558
PydanticSerializationError::new_err(format!(
558559
"Unable to serialize unknown type: {}",
559-
safe_repr(value.get_type())
560+
safe_repr(Py2::<PyType>::borrowed_from_gil_ref(&value.get_type()))
560561
))
561562
}
562563

src/serializers/type_serializers/literal.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -46,7 +46,7 @@ impl BuildSerializer for LiteralSerializer {
4646
repr_args.push(item.repr()?.extract()?);
4747
if let Ok(bool) = item.downcast::<PyBool>() {
4848
expected_py.append(bool)?;
49-
} else if let Ok(int) = extract_i64(item.as_gil_ref()) {
49+
} else if let Ok(int) = extract_i64(&item) {
5050
expected_int.insert(int);
5151
} else if let Ok(py_str) = item.downcast::<PyString>() {
5252
expected_str.insert(py_str.to_str()?.to_string());
@@ -79,7 +79,7 @@ impl LiteralSerializer {
7979
fn check<'a>(&self, value: &'a PyAny, extra: &Extra) -> PyResult<OutputValue<'a>> {
8080
if extra.check.enabled() {
8181
if !self.expected_int.is_empty() && !PyBool::is_type_of(value) {
82-
if let Ok(int) = extract_i64(value) {
82+
if let Ok(int) = extract_i64(Py2::borrowed_from_gil_ref(&value)) {
8383
if self.expected_int.contains(&int) {
8484
return Ok(OutputValue::OkInt(int));
8585
}

src/tools.rs

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@ use std::borrow::Cow;
33
use pyo3::exceptions::{PyKeyError, PyTypeError};
44
use pyo3::prelude::*;
55
use pyo3::types::{PyDict, PyInt, PyString};
6-
use pyo3::{intern, FromPyObject, PyTypeInfo};
6+
use pyo3::{intern, FromPyObject};
77

88
pub trait SchemaDict<'py> {
99
fn get_as<T>(&self, key: &PyString) -> PyResult<Option<T>>
@@ -89,18 +89,18 @@ pub fn function_name(f: &Py2<'_, PyAny>) -> PyResult<String> {
8989
}
9090
}
9191

92-
pub fn safe_repr(v: &PyAny) -> Cow<str> {
92+
pub fn safe_repr(v: &Py2<'_, PyAny>) -> Cow<'static, str> {
9393
if let Ok(s) = v.repr() {
94-
s.to_string_lossy()
94+
s.to_string_lossy().into_owned().into()
9595
} else if let Ok(name) = v.get_type().name() {
9696
format!("<unprintable {name} object>").into()
9797
} else {
9898
"<unprintable object>".into()
9999
}
100100
}
101101

102-
pub fn extract_i64(v: &PyAny) -> PyResult<i64> {
103-
if PyInt::is_type_of(v) {
102+
pub fn extract_i64(v: &Py2<'_, PyAny>) -> PyResult<i64> {
103+
if v.is_instance_of::<PyInt>() {
104104
v.extract()
105105
} else {
106106
py_err!(PyTypeError; "expected int, got {}", safe_repr(v))

src/url.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -42,7 +42,7 @@ fn build_schema_validator(py: Python, schema_type: &str) -> SchemaValidator {
4242
#[pymethods]
4343
impl PyUrl {
4444
#[new]
45-
pub fn py_new(py: Python, url: Py2<'_, PyAny>) -> PyResult<Self> {
45+
pub fn py_new(py: Python, url: &Py2<'_, PyAny>) -> PyResult<Self> {
4646
let schema_obj = SCHEMA_DEFINITION_URL
4747
.get_or_init(py, || build_schema_validator(py, "url"))
4848
.validate_python(py, url, None, None, None, None)?;
@@ -218,7 +218,7 @@ static SCHEMA_DEFINITION_MULTI_HOST_URL: GILOnceCell<SchemaValidator> = GILOnceC
218218
#[pymethods]
219219
impl PyMultiHostUrl {
220220
#[new]
221-
pub fn py_new(py: Python, url: Py2<'_, PyAny>) -> PyResult<Self> {
221+
pub fn py_new(py: Python, url: &Py2<'_, PyAny>) -> PyResult<Self> {
222222
let schema_obj = SCHEMA_DEFINITION_MULTI_HOST_URL
223223
.get_or_init(py, || build_schema_validator(py, "multi-host-url"))
224224
.validate_python(py, url, None, None, None, None)?;

src/validators/function.rs

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -521,16 +521,16 @@ impl ValidationInfo {
521521
impl ValidationInfo {
522522
fn __repr__(&self, py: Python) -> PyResult<String> {
523523
let context = match self.context {
524-
Some(ref context) => safe_repr(context.as_ref(py)),
524+
Some(ref context) => safe_repr(context.attach(py)),
525525
None => "None".into(),
526526
};
527-
let config = self.config.as_ref(py).repr()?;
527+
let config = self.config.attach(py).repr()?;
528528
let data = match self.data {
529-
Some(ref data) => safe_repr(data.as_ref(py)),
529+
Some(ref data) => safe_repr(data.attach(py)),
530530
None => "None".into(),
531531
};
532532
let field_name = match self.field_name {
533-
Some(ref field_name) => safe_repr(field_name.as_ref(py)),
533+
Some(ref field_name) => safe_repr(field_name.attach(py)),
534534
None => "None".into(),
535535
};
536536
Ok(format!(

src/validators/mod.rs

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -157,15 +157,15 @@ impl SchemaValidator {
157157
pub fn validate_python(
158158
&self,
159159
py: Python,
160-
input: Py2<'_, PyAny>,
160+
input: &Py2<'_, PyAny>,
161161
strict: Option<bool>,
162162
from_attributes: Option<bool>,
163163
context: Option<&PyAny>,
164164
self_instance: Option<&PyAny>,
165165
) -> PyResult<PyObject> {
166166
self._validate(
167167
py,
168-
&input,
168+
input,
169169
InputType::Python,
170170
strict,
171171
from_attributes,
@@ -179,15 +179,15 @@ impl SchemaValidator {
179179
pub fn isinstance_python(
180180
&self,
181181
py: Python,
182-
input: Py2<'_, PyAny>,
182+
input: &Py2<'_, PyAny>,
183183
strict: Option<bool>,
184184
from_attributes: Option<bool>,
185185
context: Option<&PyAny>,
186186
self_instance: Option<&PyAny>,
187187
) -> PyResult<bool> {
188188
match self._validate(
189189
py,
190-
&input,
190+
input,
191191
InputType::Python,
192192
strict,
193193
from_attributes,
@@ -206,15 +206,15 @@ impl SchemaValidator {
206206
pub fn validate_json(
207207
&self,
208208
py: Python,
209-
input: Py2<'_, PyAny>,
209+
input: &Py2<'_, PyAny>,
210210
strict: Option<bool>,
211211
context: Option<&PyAny>,
212212
self_instance: Option<&PyAny>,
213213
) -> PyResult<PyObject> {
214-
let r = match json::validate_json_bytes(&input) {
214+
let r = match json::validate_json_bytes(input) {
215215
Ok(v_match) => self._validate_json(
216216
py,
217-
&input,
217+
input,
218218
v_match.into_inner().as_slice(),
219219
strict,
220220
context,

src/validators/uuid.rs

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -112,7 +112,10 @@ impl Validator for UuidValidator {
112112
} else if state.strict_or(self.strict) && state.extra().input_type == InputType::Python {
113113
Err(ValError::new(
114114
ErrorType::IsInstanceOf {
115-
class: class.name().unwrap_or("UUID").to_string(),
115+
class: class
116+
.name()
117+
.and_then(|any| any.extract())
118+
.unwrap_or_else(|_| "UUID".into()),
116119
context: None,
117120
},
118121
input,

tests/test.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -128,7 +128,7 @@ json_input = '{"a": "something"}'
128128
let json_input = locals.get_item("json_input").unwrap().unwrap();
129129
let binding = SchemaValidator::py_new(py, &schema, None)
130130
.unwrap()
131-
.validate_json(py, json_input, None, None, None)
131+
.validate_json(py, &json_input, None, None, None)
132132
.unwrap();
133133
let validation_result: &PyAny = binding.extract(py).unwrap();
134134
let repr = format!("{}", validation_result.repr().unwrap());

0 commit comments

Comments
 (0)