Skip to content
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
33 changes: 33 additions & 0 deletions src/input/input_python.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ use std::str::from_utf8;
use pyo3::intern;
use pyo3::prelude::*;

use pyo3::sync::GILOnceCell;
use pyo3::types::PyType;
use pyo3::types::{
PyBool, PyByteArray, PyBytes, PyComplex, PyDate, PyDateTime, PyDict, PyFloat, PyFrozenSet, PyInt, PyIterator,
Expand Down Expand Up @@ -45,6 +46,20 @@ use super::{
Input,
};

static FRACTION_TYPE: GILOnceCell<Py<PyType>> = GILOnceCell::new();

pub fn get_fraction_type(py: Python) -> &Bound<'_, PyType> {
FRACTION_TYPE
.get_or_init(py, || {
py.import("fractions")
.and_then(|fractions_module| fractions_module.getattr("Fraction"))
.unwrap()
.extract()
.unwrap()
})
.bind(py)
}

pub(crate) fn downcast_python_input<'py, T: PyTypeCheck>(input: &(impl Input<'py> + ?Sized)) -> Option<&Bound<'py, T>> {
input.as_python().and_then(|any| any.downcast::<T>().ok())
}
Expand Down Expand Up @@ -269,6 +284,24 @@ impl<'py> Input<'py> for Bound<'py, PyAny> {
float_as_int(self, self.extract::<f64>()?)
} else if let Ok(decimal) = self.validate_decimal(true, self.py()) {
decimal_as_int(self, &decimal.into_inner())
} else if self.is_instance(get_fraction_type(self.py()))? {
#[cfg(Py_3_12)]
let is_integer = self.call_method0("is_integer")?.extract::<bool>()?;
#[cfg(not(Py_3_12))]
let is_integer = self.getattr("denominator")?.extract::<i64>().map_or(false, |d| d == 1);

if is_integer {
#[cfg(Py_3_11)]
let as_int = self.call_method0("__int__");
#[cfg(not(Py_3_11))]
let as_int = self.call_method0("__trunc__");
match as_int {
Ok(i) => Ok(EitherInt::Py(i.as_any().to_owned())),
Err(_) => break 'lax,
}
} else {
Err(ValError::new(ErrorTypeDefaults::IntFromFloat, self))
}
} else if let Ok(float) = self.extract::<f64>() {
float_as_int(self, float)
} else if let Some(enum_val) = maybe_as_enum(self) {
Expand Down
12 changes: 11 additions & 1 deletion tests/validators/test_int.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import json
import re
from decimal import Decimal
from fractions import Fraction
from typing import Any

import pytest
Expand Down Expand Up @@ -132,13 +133,22 @@ def test_int_py_and_json(py_and_json: PyAndJson, input_value, expected):
(-i64_max + 1, -i64_max + 1),
(i64_max * 2, i64_max * 2),
(-i64_max * 2, -i64_max * 2),
(Fraction(10_935_244_710_974_505), 10_935_244_710_974_505), # https://github.com/pydantic/pydantic/issues/12063
pytest.param(
Fraction(1, 2),
Err(
'Input should be a valid integer, got a number with a fractional part '
'[type=int_from_float, input_value=Fraction(1, 2), input_type=Fraction]'
),
id='fraction-remainder',
),
pytest.param(
1.00000000001,
Err(
'Input should be a valid integer, got a number with a fractional part '
'[type=int_from_float, input_value=1.00000000001, input_type=float]'
),
id='decimal-remainder',
id='float-remainder',
),
pytest.param(
Decimal('1.001'),
Expand Down
Loading