Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
24 changes: 24 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,15 @@ 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_11)]
let as_int = self.call_method0("__int__");
#[cfg(not(Py_3_11))]
let as_int = self.call_method0("__trunc__");
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not sure if there's a better way: maybe pyo3 can do the coercion directly? I've tried downcasting with no success.

match as_int {
Ok(i) => Ok(EitherInt::Py(i.as_any().to_owned())),
Err(_) => break 'lax,
}
} 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
2 changes: 2 additions & 0 deletions 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,6 +133,7 @@ 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(
1.00000000001,
Err(
Expand Down
Loading