Skip to content

Commit cbb337a

Browse files
committed
remove use of intern! and &PyString
1 parent 24ee390 commit cbb337a

Some content is hidden

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

71 files changed

+523
-524
lines changed

src/build_tools.rs

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@ use std::fmt;
44
use pyo3::exceptions::PyException;
55
use pyo3::prelude::*;
66
use pyo3::types::{PyDict, PyList, PyString};
7-
use pyo3::{intern, FromPyObject, PyErrArguments};
7+
use pyo3::{intern2, FromPyObject, PyErrArguments};
88

99
use crate::errors::ValError;
1010
use crate::input::InputType;
@@ -14,8 +14,8 @@ use crate::ValidationError;
1414
pub fn schema_or_config<'py, T>(
1515
schema: &Py2<'py, PyDict>,
1616
config: Option<&Py2<'py, PyDict>>,
17-
schema_key: &PyString,
18-
config_key: &PyString,
17+
schema_key: &Py2<'_, PyString>,
18+
config_key: &Py2<'_, PyString>,
1919
) -> PyResult<Option<T>>
2020
where
2121
T: FromPyObject<'py>,
@@ -32,7 +32,7 @@ where
3232
pub fn schema_or_config_same<'py, T>(
3333
schema: &Py2<'py, PyDict>,
3434
config: Option<&Py2<'py, PyDict>>,
35-
key: &PyString,
35+
key: &Py2<'_, PyString>,
3636
) -> PyResult<Option<T>>
3737
where
3838
T: FromPyObject<'py>,
@@ -42,7 +42,7 @@ where
4242

4343
pub fn is_strict(schema: &Py2<'_, PyDict>, config: Option<&Py2<'_, PyDict>>) -> PyResult<bool> {
4444
let py = schema.py();
45-
Ok(schema_or_config_same(schema, config, intern!(py, "strict"))?.unwrap_or(false))
45+
Ok(schema_or_config_same(schema, config, intern2!(py, "strict"))?.unwrap_or(false))
4646
}
4747

4848
enum SchemaErrorEnum {
@@ -181,8 +181,8 @@ impl ExtraBehavior {
181181
let extra_behavior = schema_or_config::<Option<Py2<'_, PyString>>>(
182182
schema,
183183
config,
184-
intern!(py, "extra_behavior"),
185-
intern!(py, "extra_fields_behavior"),
184+
intern2!(py, "extra_behavior"),
185+
intern2!(py, "extra_fields_behavior"),
186186
)?
187187
.flatten();
188188
let res = match extra_behavior.as_ref().map(|s| s.to_str()).transpose()? {

src/errors/validation_exception.rs

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@ use std::str::from_utf8;
44

55
use pyo3::exceptions::{PyKeyError, PyTypeError, PyValueError};
66
use pyo3::ffi;
7-
use pyo3::intern;
7+
use pyo3::intern2;
88
use pyo3::prelude::*;
99
use pyo3::sync::GILOnceCell;
1010
use pyo3::types::{PyDict, PyList, PyString};
@@ -444,11 +444,11 @@ impl TryFrom<&Py2<'_, PyAny>> for PyLineError {
444444
let py = value.py();
445445

446446
let type_raw = dict
447-
.get_item(intern!(py, "type"))?
447+
.get_item(intern2!(py, "type"))?
448448
.ok_or_else(|| PyKeyError::new_err("type"))?;
449449

450450
let error_type = if let Ok(type_str) = type_raw.downcast::<PyString>() {
451-
let context: Option<&PyDict> = dict.get_as(intern!(py, "ctx"))?;
451+
let context: Option<&PyDict> = dict.get_as(intern2!(py, "ctx"))?;
452452
ErrorType::new(py, type_str.to_str()?, context)?
453453
} else if let Ok(custom_error) = type_raw.extract::<PydanticCustomError>() {
454454
ErrorType::new_custom_error(py, custom_error)

src/input/datetime.rs

Lines changed: 16 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
use pyo3::intern;
1+
use pyo3::intern2;
22
use pyo3::prelude::*;
33

44
use pyo3::exceptions::PyValueError;
@@ -38,9 +38,9 @@ impl<'a> From<Py2<'a, PyDate>> for EitherDate<'a> {
3838
pub fn pydate_as_date(py_date: &Py2<'_, PyAny>) -> PyResult<Date> {
3939
let py = py_date.py();
4040
Ok(Date {
41-
year: py_date.getattr(intern!(py, "year"))?.extract()?,
42-
month: py_date.getattr(intern!(py, "month"))?.extract()?,
43-
day: py_date.getattr(intern!(py, "day"))?.extract()?,
41+
year: py_date.getattr(intern2!(py, "year"))?.extract()?,
42+
month: py_date.getattr(intern2!(py, "month"))?.extract()?,
43+
day: py_date.getattr(intern2!(py, "day"))?.extract()?,
4444
})
4545
}
4646

@@ -148,7 +148,7 @@ pub fn pytimedelta_exact_as_duration(py_timedelta: &Py2<'_, PyDelta>) -> Duratio
148148

149149
pub fn pytimedelta_subclass_as_duration(py_timedelta: &Py2<'_, PyDelta>) -> PyResult<Duration> {
150150
let total_seconds: f64 = py_timedelta
151-
.call_method0(intern!(py_timedelta.py(), "total_seconds"))?
151+
.call_method0(intern2!(py_timedelta.py(), "total_seconds"))?
152152
.extract()?;
153153
if total_seconds.is_nan() {
154154
return py_err!(PyValueError; "NaN values not permitted");
@@ -176,25 +176,25 @@ pub fn duration_as_pytimedelta<'py>(py: Python<'py>, duration: &Duration) -> PyR
176176
pub fn pytime_as_time(py_time: &Py2<'_, PyAny>, py_dt: Option<&Py2<'_, PyAny>>) -> PyResult<Time> {
177177
let py = py_time.py();
178178

179-
let tzinfo = py_time.getattr(intern!(py, "tzinfo"))?;
179+
let tzinfo = py_time.getattr(intern2!(py, "tzinfo"))?;
180180
let tz_offset: Option<i32> = if PyAnyMethods::is_none(&tzinfo) {
181181
None
182182
} else {
183-
let offset_delta = tzinfo.call_method1(intern!(py, "utcoffset"), (py_dt,))?;
183+
let offset_delta = tzinfo.call_method1(intern2!(py, "utcoffset"), (py_dt,))?;
184184
// as per the docs, utcoffset() can return None
185185
if PyAnyMethods::is_none(&offset_delta) {
186186
None
187187
} else {
188-
let offset_seconds: f64 = offset_delta.call_method0(intern!(py, "total_seconds"))?.extract()?;
188+
let offset_seconds: f64 = offset_delta.call_method0(intern2!(py, "total_seconds"))?.extract()?;
189189
Some(offset_seconds.round() as i32)
190190
}
191191
};
192192

193193
Ok(Time {
194-
hour: py_time.getattr(intern!(py, "hour"))?.extract()?,
195-
minute: py_time.getattr(intern!(py, "minute"))?.extract()?,
196-
second: py_time.getattr(intern!(py, "second"))?.extract()?,
197-
microsecond: py_time.getattr(intern!(py, "microsecond"))?.extract()?,
194+
hour: py_time.getattr(intern2!(py, "hour"))?.extract()?,
195+
minute: py_time.getattr(intern2!(py, "minute"))?.extract()?,
196+
second: py_time.getattr(intern2!(py, "second"))?.extract()?,
197+
microsecond: py_time.getattr(intern2!(py, "microsecond"))?.extract()?,
198198
tz_offset,
199199
})
200200
}
@@ -390,13 +390,13 @@ pub fn float_as_datetime<'a>(input: &'a impl Input<'a>, timestamp: f64) -> ValRe
390390
int_as_datetime(input, timestamp.floor() as i64, microseconds.round() as u32)
391391
}
392392

393-
pub fn date_as_datetime(date: &PyDate) -> PyResult<EitherDateTime> {
393+
pub fn date_as_datetime<'py>(date: &Py2<'py, PyDate>) -> PyResult<EitherDateTime<'py>> {
394394
let py = date.py();
395395
let dt = PyDateTime::new2(
396396
py,
397-
date.getattr(intern!(py, "year"))?.extract()?,
398-
date.getattr(intern!(py, "month"))?.extract()?,
399-
date.getattr(intern!(py, "day"))?.extract()?,
397+
date.getattr(intern2!(py, "year"))?.extract()?,
398+
date.getattr(intern2!(py, "month"))?.extract()?,
399+
date.getattr(intern2!(py, "day"))?.extract()?,
400400
0,
401401
0,
402402
0,

src/input/input_abstract.rs

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@ use std::fmt;
22

33
use pyo3::exceptions::PyValueError;
44
use pyo3::types::{PyDict, PyType};
5-
use pyo3::{intern, prelude::*};
5+
use pyo3::{intern2, prelude::*};
66

77
use crate::errors::{AsLocItem, ErrorTypeDefaults, InputValue, ValError, ValResult};
88
use crate::tools::py_err;
@@ -22,9 +22,9 @@ pub enum InputType {
2222
impl IntoPy<PyObject> for InputType {
2323
fn into_py(self, py: Python<'_>) -> PyObject {
2424
match self {
25-
Self::Json => intern!(py, "json").into(),
26-
Self::Python => intern!(py, "python").into(),
27-
Self::String => intern!(py, "string").into(),
25+
Self::Json => intern2!(py, "json").into_py(py),
26+
Self::Python => intern2!(py, "python").into_py(py),
27+
Self::String => intern2!(py, "string").into_py(py),
2828
}
2929
}
3030
}
@@ -67,7 +67,7 @@ pub trait Input<'a>: fmt::Debug + ToPyObject + AsLocItem + Sized {
6767

6868
fn as_kwargs(&self, py: Python<'a>) -> Option<Py2<'a, PyDict>>;
6969

70-
fn input_is_subclass(&self, _class: &PyType) -> PyResult<bool> {
70+
fn input_is_subclass(&self, _class: &Py2<'_, PyType>) -> PyResult<bool> {
7171
Ok(false)
7272
}
7373

src/input/input_python.rs

Lines changed: 16 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,14 @@
11
use std::borrow::Cow;
22
use std::str::from_utf8;
33

4+
use pyo3::intern2;
45
use pyo3::prelude::*;
56
use pyo3::types::{
67
PyBool, PyByteArray, PyBytes, PyDate, PyDateTime, PyDict, PyFloat, PyFrozenSet, PyInt, PyIterator, PyList,
78
PyMapping, PySequence, PySet, PyString, PyTime, PyTuple, PyType,
89
};
910
#[cfg(not(PyPy))]
1011
use pyo3::types::{PyDictItems, PyDictKeys, PyDictValues};
11-
use pyo3::{intern, PyTypeInfo};
1212

1313
use speedate::MicrosecondsPrecisionOverflowBehavior;
1414

@@ -121,9 +121,9 @@ impl<'a> Input<'a> for Py2<'a, PyAny> {
121121
self.downcast::<PyDict>().ok().map(Clone::clone)
122122
}
123123

124-
fn input_is_subclass(&self, class: &PyType) -> PyResult<bool> {
124+
fn input_is_subclass(&self, class: &Py2<'_, PyType>) -> PyResult<bool> {
125125
match self.downcast::<PyType>() {
126-
Ok(py_type) => py_type.as_gil_ref().is_subclass(class),
126+
Ok(py_type) => py_type.is_subclass(class),
127127
Err(_) => Ok(false),
128128
}
129129
}
@@ -204,7 +204,7 @@ impl<'a> Input<'a> for Py2<'a, PyAny> {
204204
Ok(s) => Ok(PyString::new2(self.py(), s).into()),
205205
Err(_) => Err(ValError::new(ErrorTypeDefaults::StringUnicode, self)),
206206
}
207-
} else if coerce_numbers_to_str && !PyBool::is_exact_type_of(self.as_gil_ref()) && {
207+
} else if coerce_numbers_to_str && !self.is_exact_instance_of::<PyBool>() && {
208208
let py = self.py();
209209
let decimal_type = get_decimal_type(py);
210210

@@ -235,7 +235,7 @@ impl<'a> Input<'a> for Py2<'a, PyAny> {
235235
}
236236

237237
fn exact_int(&'a self) -> ValResult<EitherInt<'a>> {
238-
if PyInt::is_exact_type_of(self.as_gil_ref()) {
238+
if self.is_exact_instance_of::<PyInt>() {
239239
Ok(EitherInt::Py(self.clone()))
240240
} else {
241241
Err(ValError::new(ErrorTypeDefaults::IntType, self))
@@ -244,9 +244,9 @@ impl<'a> Input<'a> for Py2<'a, PyAny> {
244244

245245
fn validate_bytes(&'a self, strict: bool) -> ValResult<ValidationMatch<EitherBytes<'a>>> {
246246
if let Ok(py_bytes) = self.downcast_exact::<PyBytes>() {
247-
return Ok(ValidationMatch::exact(py_bytes.as_gil_ref().into()));
247+
return Ok(ValidationMatch::exact(py_bytes.into()));
248248
} else if let Ok(py_bytes) = self.downcast::<PyBytes>() {
249-
return Ok(ValidationMatch::strict(py_bytes.as_gil_ref().into()));
249+
return Ok(ValidationMatch::strict(py_bytes.into()));
250250
}
251251

252252
'lax: {
@@ -304,7 +304,7 @@ impl<'a> Input<'a> for Py2<'a, PyAny> {
304304
};
305305

306306
// force to an int to upcast to a pure python int
307-
return EitherInt::upcast(self.as_gil_ref()).map(|either_int| ValidationMatch::new(either_int, exactness));
307+
return EitherInt::upcast(self).map(|either_int| ValidationMatch::new(either_int, exactness));
308308
}
309309

310310
'lax: {
@@ -331,7 +331,7 @@ impl<'a> Input<'a> for Py2<'a, PyAny> {
331331

332332
fn validate_float(&'a self, strict: bool) -> ValResult<ValidationMatch<EitherFloat<'a>>> {
333333
if let Ok(float) = self.downcast_exact::<PyFloat>() {
334-
return Ok(ValidationMatch::exact(EitherFloat::Py(float.as_gil_ref())));
334+
return Ok(ValidationMatch::exact(EitherFloat::Py(float.clone())));
335335
}
336336

337337
if !strict {
@@ -565,7 +565,7 @@ impl<'a> Input<'a> for Py2<'a, PyAny> {
565565

566566
fn validate_iter(&self) -> ValResult<GenericIterator> {
567567
if self.iter().is_ok() {
568-
Ok(self.as_gil_ref().into())
568+
Ok(self.into())
569569
} else {
570570
Err(ValError::new(ErrorTypeDefaults::IterableType, self))
571571
}
@@ -574,7 +574,7 @@ impl<'a> Input<'a> for Py2<'a, PyAny> {
574574
fn validate_date(&self, strict: bool) -> ValResult<ValidationMatch<EitherDate>> {
575575
if let Ok(date) = self.downcast_exact::<PyDate>() {
576576
Ok(ValidationMatch::exact(date.clone().into()))
577-
} else if PyDateTime::is_type_of(self.as_gil_ref()) {
577+
} else if self.is_instance_of::<PyDateTime>() {
578578
// have to check if it's a datetime first, otherwise the line below converts to a date
579579
// even if we later try coercion from a datetime, we don't want to return a datetime now
580580
Err(ValError::new(ErrorTypeDefaults::DateType, self))
@@ -616,7 +616,7 @@ impl<'a> Input<'a> for Py2<'a, PyAny> {
616616
bytes_as_time(self, str.as_bytes(), microseconds_overflow_behavior)
617617
} else if let Ok(py_bytes) = self.downcast::<PyBytes>() {
618618
bytes_as_time(self, py_bytes.as_bytes(), microseconds_overflow_behavior)
619-
} else if PyBool::is_exact_type_of(self.as_gil_ref()) {
619+
} else if self.is_exact_instance_of::<PyBool>() {
620620
Err(ValError::new(ErrorTypeDefaults::TimeType, self))
621621
} else if let Ok(int) = extract_i64(self) {
622622
int_as_time(self, int, 0)
@@ -650,14 +650,14 @@ impl<'a> Input<'a> for Py2<'a, PyAny> {
650650
bytes_as_datetime(self, str.as_bytes(), microseconds_overflow_behavior)
651651
} else if let Ok(py_bytes) = self.downcast::<PyBytes>() {
652652
bytes_as_datetime(self, py_bytes.as_bytes(), microseconds_overflow_behavior)
653-
} else if PyBool::is_exact_type_of(self.as_gil_ref()) {
653+
} else if self.is_exact_instance_of::<PyBool>() {
654654
Err(ValError::new(ErrorTypeDefaults::DatetimeType, self))
655655
} else if let Ok(int) = extract_i64(self) {
656656
int_as_datetime(self, int, 0)
657657
} else if let Ok(float) = self.extract::<f64>() {
658658
float_as_datetime(self, float)
659659
} else if let Ok(date) = self.downcast::<PyDate>() {
660-
Ok(date_as_datetime(date.as_gil_ref())?)
660+
Ok(date_as_datetime(date)?)
661661
} else {
662662
break 'lax;
663663
}
@@ -735,7 +735,7 @@ impl BorrowInput for Py2Borrowed<'_, '_, PyAny> {
735735
fn from_attributes_applicable(obj: &Py2<'_, PyAny>) -> bool {
736736
let Some(module_name) = obj
737737
.get_type()
738-
.getattr(intern!(obj.py(), "__module__"))
738+
.getattr(intern2!(obj.py(), "__module__"))
739739
.ok()
740740
.and_then(|module_name| module_name.downcast_into::<PyString>().ok())
741741
else {
@@ -769,7 +769,7 @@ fn maybe_as_enum<'py>(v: &Py2<'py, PyAny>) -> Option<Py2<'py, PyAny>> {
769769
let enum_meta_object = get_enum_meta_object(py);
770770
let meta_type = v.get_type().get_type();
771771
if meta_type.is(enum_meta_object) {
772-
v.getattr(intern!(py, "value")).ok()
772+
v.getattr(intern2!(py, "value")).ok()
773773
} else {
774774
None
775775
}

0 commit comments

Comments
 (0)