Backtestspydanticrun-20261003-150343#13257
'fraction_validator' raises unhandled 'ZeroDivisionError' for zero-denominator string input instead of 'ValidationError'
Our patch was judged better than the merged fix.
In this judgment, Patch A = our agent, Patch B = the merged fix.
Both patches make zero-denominator strings like '6/0' raise ValidationError (fraction_parsing) instead of ZeroDivisionError. Patch A does it with the minimal root-cause fix the issue proposes: it adds ZeroDivisionError to the except tuple in fraction_validator. It adds targeted tests covering validate_python, validate_strings and validate_json for '6/0', '-1/0' and '0/0', and updates the existing tests that expected ZeroDivisionError. Those tests would fail before the change and pass after it. Patch B is a large redesign. It adds a new Rust FractionValidator and FractionSerializer in pydantic-core, a new core_schema.fraction_schema, new error types, ObType changes, changes to int coercion through a rewritten fraction_as_int, JSON schema changes (validation mode now emits anyOf number/string, which is a behavior change), and docs. It deletes the Python fraction_validator and several existing tests. That scope adds substantial risk: it changes public JSON schema output, serialization paths, error types for non-string inputs (TypeError/OverflowError now become ValidationErrors), and int-from-fraction behavior. It also removes tests (test_fraction_validation, the lax/strict/serialization tests) rather than preserving coverage, and it touches the compiled core, which is far heavier than the issue warrants. Patch B is arguably more thorough in also handling OverflowError and TypeError, but that is beyond the ask and obscures the fix. Patch A is correct, well-tested, minimal and consistent with the surrounding conventions.
The judge saw only the two patches, labelled A and B in random order, with issue links and version numbers removed. The reasoning above is shown verbatim.
Solve
30m 7s
Wall-clock time in the container
Full test suite
No new failures
12,245 passed · 500 skipped · 12,745 total
Contamination audit
Clean
No sign the agent saw the real fix
Patch size
32vs 661 merged
Changed lines, ours vs merged
The issue
View on GitHubInitial Checks
- I confirm that I'm using Pydantic V2
Description
Bug description
The fraction_validator in pydantic/_internal/_validators.py only catches ValueError when constructing a fractions.Fraction from user input. However, Python's standard fractions.Fraction raises ZeroDivisionError when the denominator is zero (e.g., the string "6/0"). Because this exception is not caught, it bubbles up as a raw Python exception instead of being converted into a ValidationError, violating Pydantic's contract that all invalid user input should result in a ValidationError.
This was discovered during fuzzing of TypeAdapter.validate_strings() with the Atheris fuzzer.
Expected behavior
A pydantic.ValidationError should be raised with a message indicating that the input is not a valid fraction.
Actual behavior
Traceback (most recent call last):
File ".../pydantic/_internal/_validators.py", line 253, in fraction_validator
return Fraction(input_value)
^^^^^^^^^^^^^^^^^^^^^
File ".../fractions.py", line 281, in __new__
raise ZeroDivisionError('Fraction(%s, 0)' % numerator)
ZeroDivisionError: Fraction(6, 0)
Root cause
In pydantic/_internal/_validators.py, line 247-254:
def fraction_validator(input_value: Any, /) -> Fraction:
if isinstance(input_value, Fraction):
return input_value
try:
return Fraction(input_value)
except ValueError:
raise PydanticCustomError('fraction_parsing', 'Input is not a valid fraction')
The except clause only catches ValueError, but Fraction("6/0") raises ZeroDivisionError.
Proposed fix
Add ZeroDivisionError to the exception tuple:
--- a/pydantic/_internal/_validators.py
+++ b/pydantic/_internal/_validators.py
@@ -250,7 +250,7 @@ def fraction_validator(input_value: Any, /) -> Fraction:
try:
return Fraction(input_value)
- except ValueError:
+ except (ValueError, ZeroDivisionError):
raise PydanticCustomError('fraction_parsing', 'Input is not a valid fraction')
This is consistent with how other validators in the same file handle exceptions from standard library constructors (e.g., decimal_validator, uuid_validator, ip_*_validators).
The bug exists and not fixed in 'main' branch as well.
Example Code
from pydantic import TypeAdapter
import fractions
adapter = TypeAdapter(fractions.Fraction)
# This should raise ValidationError, but raises ZeroDivisionError
adapter.validate_strings("6/0")
Python, Pydantic & OS Version
pydantic version: 2.12.5
pydantic-core version: 2.41.5
pydantic-core build: profile=release pgo=false
python version: 3.12.10 (main, May 28 2026, 03:57:43) [GCC 11.4.0]
platform: Linux-6.17.0-29-generic-x86_64-with-glibc2.35
related packages: typing_extensions-4.15.0
commit: unknownThe two patches
pydantic/_internal/_validators.pyindex a6baa54e..3e6a6742 100644@@ -252,7 +252,7 @@ def fraction_validator(input_value: Any, /) -> Fraction: try: return Fraction(input_value)- except ValueError:+ except (ValueError, ZeroDivisionError): raise PydanticCustomError('fraction_parsing', 'Input is not a valid fraction') tests/test_types.pyindex 03753317..b3afa2f9 100644@@ -7162,6 +7162,32 @@ def test_fraction_validation_lax(input_data) -> None: assert isinstance(fraction, Fraction) +@pytest.mark.parametrize('input_data', ['6/0', '-1/0', '0/0'])+def test_fraction_validation_zero_denominator_python(input_data) -> None:+ ta = TypeAdapter(Fraction)+ with pytest.raises(ValidationError) as exc_info:+ ta.validate_python(input_data)+ assert exc_info.value.errors(include_url=False) == [+ {'type': 'fraction_parsing', 'loc': (), 'msg': 'Input is not a valid fraction', 'input': input_data}+ ]+++@pytest.mark.parametrize('input_data', ['6/0', '-1/0', '0/0'])+def test_fraction_validation_zero_denominator_strings_and_json(input_data) -> None:+ ta = TypeAdapter(Fraction)+ with pytest.raises(ValidationError) as exc_info:+ ta.validate_strings(input_data)+ assert exc_info.value.errors(include_url=False) == [+ {'type': 'fraction_parsing', 'loc': (), 'msg': 'Input is not a valid fraction', 'input': input_data}+ ]++ with pytest.raises(ValidationError) as exc_info:+ ta.validate_json(f'"{input_data}"')+ assert exc_info.value.errors(include_url=False) == [+ {'type': 'fraction_parsing', 'loc': (), 'msg': 'Input is not a valid fraction', 'input': input_data}+ ]++ def test_fraction_validation_strict() -> None: ta = TypeAdapter(Fraction, config=ConfigDict(strict=True)) tests/types/test_fraction.pyindex bb5b6ee1..57956590 100644@@ -72,7 +72,7 @@ def test_fraction_validate_json(json_str, expected): 'json_str,error', [ ('"not a number"', ValidationError),- ('"1/0"', ZeroDivisionError),+ ('"1/0"', ValidationError), (float('inf'), ValidationError), (float('nan'), ValidationError), ],@@ -127,7 +127,7 @@ def test_fraction_strict_accepts_fraction(input_value): 'input_value,error', [ ('not a number', ValidationError),- ('1/0', ZeroDivisionError),+ ('1/0', ValidationError), (float('inf'), OverflowError), (float('nan'), ValidationError), ([1, 2], TypeError),
docs/errors/validation_errors.mdindex 4ca0a48b5..84654f073 100644@@ -826,6 +826,48 @@ except ValidationError as exc: #> 'float_type' ``` +## `fraction_parsing`++This error is raised when the value provided for an input that could not be parsed as a fraction:++```python+from fractions import Fraction++from pydantic import BaseModel, ValidationError+++class Model(BaseModel):+ x: Fraction+++try:+ Model(x='invalid')+except ValidationError as exc:+ print(repr(exc.errors()[0]['type']))+ #> 'fraction_parsing'+```++## `fraction_type`++This error is raised when the value provided for a [`Fraction`][fractions.Fraction] is of the wrong type:++```python+from fractions import Fraction++from pydantic import BaseModel, ValidationError+++class Model(BaseModel):+ x: Fraction+++try:+ Model.model_validate_json('{"x": [1, 2]}')+except ValidationError as exc:+ print(repr(exc.errors()[0]['type']))+ #> 'fraction_type'+```+ ## `frozen_field` This error is raised when you attempt to assign a value to a field with `frozen=True`, or to delete such a field:pydantic-core/python/pydantic_core/core_schema.pyindex 15d785653..c6118a082 100644@@ -10,6 +10,7 @@ import warnings from collections.abc import Callable, Generator, Hashable, Mapping from datetime import date, datetime, time, timedelta from decimal import Decimal+from fractions import Fraction from re import Pattern from typing import TYPE_CHECKING, Any, Literal @@ -834,6 +835,64 @@ def decimal_schema( ) +class FractionSchema(TypedDict, total=False):+ type: Required[Literal['fraction']]+ le: Fraction+ ge: Fraction+ lt: Fraction+ gt: Fraction+ strict: bool+ ref: str+ metadata: dict[str, Any]+ serialization: SerSchema+++def fraction_schema(+ *,+ le: Fraction | None = None,+ ge: Fraction | None = None,+ lt: Fraction | None = None,+ gt: Fraction | None = None,+ strict: bool | None = None,+ ref: str | None = None,+ metadata: dict[str, Any] | None = None,+ serialization: SerSchema | None = None,+) -> FractionSchema:+ """+ Returns a schema that matches a fraction value, e.g.:++ ```py+ from fractions import Fraction+ from pydantic_core import SchemaValidator, core_schema++ schema = core_schema.fraction_schema(le=Fraction(3, 4), ge=Fraction(1, 4))+ v = SchemaValidator(schema)+ assert v.validate_python('1/2') == Fraction(1, 2)+ ```++ Args:+ le: The value must be less than or equal to this number+ ge: The value must be greater than or equal to this number+ lt: The value must be strictly less than this number+ gt: The value must be strictly greater than this number+ strict: Whether the value should be a Fraction or a value that can be converted to a Fraction+ ref: optional unique identifier of the schema, used to reference the schema in other places+ metadata: Any other information you want to include with the schema, not used by pydantic-core+ serialization: Custom serialization schema+ """+ return _dict_not_none(+ type='fraction',+ gt=gt,+ ge=ge,+ lt=lt,+ le=le,+ strict=strict,+ ref=ref,+ metadata=metadata,+ serialization=serialization,+ )++ class ComplexSchema(TypedDict, total=False): type: Required[Literal['complex']] strict: bool@@ -4133,6 +4192,7 @@ if not MYPY: | IntSchema | FloatSchema | DecimalSchema+ | FractionSchema | StringSchema | BytesSchema | DateSchema@@ -4192,6 +4252,7 @@ CoreSchemaType: TypeAlias = Literal[ 'int', 'float', 'decimal',+ 'fraction', 'str', 'bytes', 'date',@@ -4347,6 +4408,8 @@ ErrorType: TypeAlias = Literal[ 'decimal_max_digits', 'decimal_max_places', 'decimal_whole_digits',+ 'fraction_type',+ 'fraction_parsing', 'complex_type', 'complex_str_parsing', ]pydantic-core/src/errors/types.rsindex 7b72e57e0..da9cdae0c 100644@@ -436,6 +436,9 @@ error_types! { DecimalWholeDigits { whole_digits: {ctx_type: u64, ctx_fn: field_from_context}, },+ // Fraction errors+ FractionType {},+ FractionParsing {}, // Complex errors ComplexType {}, ComplexStrParsing {},@@ -604,6 +607,8 @@ impl ErrorType { Self::DecimalWholeDigits { .. } => { "Decimal input should have no more than {whole_digits} digit{expected_plural} before the decimal point" }+ Self::FractionParsing { .. } => "Input is not a valid fraction",+ Self::FractionType { .. } => "Fraction input should be an integer, float, string or Fraction object", Self::ComplexType { .. } => { "Input should be a valid python complex object, a number, or a valid complex string following the rules at https://docs.python.org/3/library/functions.html#complex" }pydantic-core/src/input/input_abstract.rsindex 37f127280..2f3a57458 100644@@ -120,6 +120,8 @@ pub(crate) trait Input<'py>: fmt::Debug { fn validate_decimal(&self, strict: bool, py: Python<'py>) -> ValMatch<Bound<'py, PyAny>>; + fn validate_fraction(&self, strict: bool, py: Python<'py>) -> ValMatch<Bound<'py, PyAny>>;+ type Dict<'a>: ValidatedDict<'py> where Self: 'a;pydantic-core/src/input/input_json.rsindex 900a499ba..41fbed72f 100644@@ -13,6 +13,7 @@ use crate::input::return_enums::EitherComplex; use crate::lookup_key::LookupPath; use crate::validators::complex::string_to_complex; use crate::validators::decimal::create_decimal;+use crate::validators::fraction::create_fraction; use crate::validators::{TemporalUnitMode, ValBytesMode}; use super::datetime::{@@ -207,6 +208,18 @@ impl<'py, 'data> Input<'py> for JsonValue<'data> { } } + fn validate_fraction(&self, _strict: bool, py: Python<'py>) -> ValMatch<Bound<'py, PyAny>> {+ match self {+ JsonValue::Float(f) => {+ create_fraction(&PyString::new(py, &f.to_string()), self).map(ValidationMatch::strict)+ }+ JsonValue::Str(..) | JsonValue::Int(..) | JsonValue::BigInt(..) => {+ create_fraction(&self.into_pyobject(py)?, self).map(ValidationMatch::strict)+ }+ _ => Err(ValError::new(ErrorTypeDefaults::FractionType, self)),+ }+ }+ type Dict<'a> = &'a JsonObject<'data> where@@ -462,6 +475,10 @@ impl<'py> Input<'py> for str { create_decimal(self.into_pyobject(py)?.as_any(), self).map(ValidationMatch::lax) } + fn validate_fraction(&self, _strict: bool, py: Python<'py>) -> ValMatch<Bound<'py, PyAny>> {+ create_fraction(self.into_pyobject(py)?.as_any(), self).map(ValidationMatch::lax)+ }+ type Dict<'a> = Never; #[cfg_attr(has_coverage_attribute, coverage(off))]pydantic-core/src/input/input_python.rsindex af6fe0475..109544375 100644@@ -3,7 +3,6 @@ use std::str::from_utf8; use pyo3::intern; use pyo3::prelude::*; -use pyo3::sync::PyOnceLock; use pyo3::types::PyType; use pyo3::types::{ PyBool, PyByteArray, PyBytes, PyComplex, PyDate, PyDateTime, PyDict, PyFloat, PyFrozenSet, PyInt, PyIterator,@@ -23,6 +22,7 @@ use crate::validators::TemporalUnitMode; use crate::validators::ValBytesMode; use crate::validators::complex::{get_complex_type, string_to_complex}; use crate::validators::decimal::{create_decimal, get_decimal_type};+use crate::validators::fraction::{create_fraction, get_fraction_type}; use super::Arguments; use super::ConsumeIterator;@@ -49,20 +49,6 @@ use super::{ py_string_str, }; -static FRACTION_TYPE: PyOnceLock<Py<PyType>> = PyOnceLock::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.cast::<T>().ok()) }@@ -285,8 +271,8 @@ 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()))? {- fraction_as_int(self)+ } else if let Ok(fraction) = self.validate_fraction(true, self.py()) {+ fraction_as_int(self, &fraction.into_inner()) } else if let Ok(float) = self.extract::<f64>() { float_as_int(self, float) } else if let Some(enum_val) = maybe_as_enum(self) {@@ -342,6 +328,35 @@ impl<'py> Input<'py> for Bound<'py, PyAny> { Err(ValError::new(ErrorTypeDefaults::FloatType, self)) } + fn validate_fraction(&self, strict: bool, py: Python<'py>) -> ValMatch<Bound<'py, PyAny>> {+ let fraction_type = get_fraction_type(py);++ // Fast path for existing fraction objects+ if self.is_exact_instance(fraction_type) {+ return Ok(ValidationMatch::exact(self.to_owned().clone()));+ }++ // Check for fraction subclasses+ if self.is_instance(fraction_type)? {+ return Ok(ValidationMatch::lax(self.to_owned().clone()));+ }++ if !strict {+ return create_fraction(self, self).map(ValidationMatch::lax);+ }++ Err(ValError::new(+ ErrorType::IsInstanceOf {+ class: fraction_type+ .qualname()+ .and_then(|name| name.extract())+ .unwrap_or_else(|_| "Fraction".to_owned()),+ context: None,+ },+ self,+ ))+ }+ fn validate_decimal(&self, strict: bool, py: Python<'py>) -> ValMatch<Bound<'py, PyAny>> { let decimal_type = get_decimal_type(py); pydantic-core/src/input/input_string.rsindex 63484dee5..b6266a0ba 100644@@ -9,6 +9,7 @@ use crate::lookup_key::LookupPath; use crate::tools::safe_repr; use crate::validators::complex::string_to_complex; use crate::validators::decimal::create_decimal;+use crate::validators::fraction::create_fraction; use crate::validators::{TemporalUnitMode, ValBytesMode}; use super::datetime::{@@ -157,6 +158,13 @@ impl<'py> Input<'py> for StringMapping<'py> { } } + fn validate_fraction(&self, _strict: bool, _py: Python<'py>) -> ValMatch<Bound<'py, PyAny>> {+ match self {+ Self::String(s) => create_fraction(s, self).map(ValidationMatch::strict),+ Self::Mapping(_) => Err(ValError::new(ErrorTypeDefaults::FractionType, self)),+ }+ }+ type Dict<'a> = StringMappingDict<'py> wherepydantic-core/src/input/shared.rsindex 1a1b490fd..29116eba5 100644@@ -228,22 +228,17 @@ pub fn decimal_as_int<'py>( Ok(EitherInt::Py(numerator)) } -pub fn fraction_as_int<'py>(input: &Bound<'py, PyAny>) -> ValResult<EitherInt<'py>> {- #[cfg(Py_3_12)]- let is_integer = input.call_method0("is_integer")?.extract::<bool>()?;- #[cfg(not(Py_3_12))]- let is_integer = input.getattr("denominator")?.extract::<i64>().is_ok_and(|d| d == 1);-- if is_integer {- #[cfg(Py_3_11)]- let as_int = input.call_method0("__int__");- #[cfg(not(Py_3_11))]- let as_int = input.call_method0("__trunc__");- match as_int {- Ok(i) => Ok(EitherInt::Py(i.as_any().to_owned())),- Err(_) => Err(ValError::new(ErrorTypeDefaults::IntType, input)),- }- } else {- Err(ValError::new(ErrorTypeDefaults::IntFromFloat, input))+pub fn fraction_as_int<'py>(+ input: &(impl Input<'py> + ?Sized),+ fraction: &Bound<'py, PyAny>,+) -> ValResult<EitherInt<'py>> {+ let py = fraction.py();++ let (numerator, denominator) = fraction+ .call_method0(intern!(py, "as_integer_ratio"))?+ .extract::<(Bound<'_, PyAny>, Bound<'_, PyAny>)>()?;+ if denominator.extract::<i64>().map_or(true, |d| d != 1) {+ return Err(ValError::new(ErrorTypeDefaults::IntFromFloat, input)); }+ Ok(EitherInt::Py(numerator)) }pydantic-core/src/serializers/infer.rsindex c4a3591ac..141a4d5fd 100644@@ -112,7 +112,7 @@ pub(crate) fn infer_to_python_known<'py>( } v.into_py_any(py)? }- ObType::Decimal => value.to_string().into_py_any(py)?,+ ObType::Decimal | ObType::Fraction => value.to_string().into_py_any(py)?, ObType::StrSubclass => PyString::new(py, value.cast::<PyString>()?.to_str()?).into(), ObType::Bytes => state .config@@ -251,6 +251,7 @@ pub(crate) fn infer_to_python_known<'py>( let v = value.cast::<PyComplex>()?; v.into_py_any(py)? }+ ObType::Fraction => value.to_string().into_py_any(py)?, ObType::Unknown => { if let Some(fallback) = &state.extra.fallback { let next_value = fallback.call1((value,))?;@@ -367,7 +368,7 @@ pub(crate) fn infer_serialize_known<'py, S: Serializer>( let v = value.extract::<f64>().map_err(py_err_se_err)?; type_serializers::float::serialize_f64(v, serializer, state.config.inf_nan_mode) }- ObType::Decimal => value.to_string().serialize(serializer),+ ObType::Decimal | ObType::Fraction => value.to_string().serialize(serializer), ObType::Str | ObType::StrSubclass => { let py_str = value.cast::<PyString>().map_err(py_err_se_err)?; serialize_to_json(serializer)@@ -509,7 +510,7 @@ pub(crate) fn infer_json_key_known<'a, 'py>( super::type_serializers::simple::to_str_json_key(key) } }- ObType::Decimal => Ok(Cow::Owned(key.to_string())),+ ObType::Decimal | ObType::Fraction => Ok(Cow::Owned(key.to_string())), ObType::Bool => super::type_serializers::simple::bool_json_key(key), ObType::Str | ObType::StrSubclass => key.cast::<PyString>()?.to_cow(), ObType::Bytes => statepydantic-core/src/serializers/ob_type.rsindex f9985e9e7..ff6b0af5d 100644@@ -23,6 +23,7 @@ pub struct ObTypeLookup { dict: usize, // other numeric types decimal_object: Py<PyAny>,+ fraction_object: Py<PyAny>, // other string types bytes: usize, bytearray: usize,@@ -76,6 +77,7 @@ impl ObTypeLookup { list: PyList::type_object_raw(py) as usize, dict: PyDict::type_object_raw(py) as usize, decimal_object: py.import("decimal").unwrap().getattr("Decimal").unwrap().unbind(),+ fraction_object: py.import("fractions").unwrap().getattr("Fraction").unwrap().unbind(), string: PyString::type_object_raw(py) as usize, bytes: PyBytes::type_object_raw(py) as usize, bytearray: PyByteArray::type_object_raw(py) as usize,@@ -148,6 +150,7 @@ impl ObTypeLookup { ObType::List => self.list == ob_type, ObType::Dict => self.dict == ob_type, ObType::Decimal => self.decimal_object.as_ptr() as usize == ob_type,+ ObType::Fraction => self.fraction_object.as_ptr() as usize == ob_type, ObType::StrSubclass => self.string == ob_type && op_value.is_none(), ObType::Tuple => self.tuple == ob_type, ObType::Set => self.set == ob_type,@@ -229,6 +232,8 @@ impl ObTypeLookup { ObType::Dict } else if ob_type == self.decimal_object.as_ptr() as usize { ObType::Decimal+ } else if ob_type == self.fraction_object.as_ptr() as usize {+ ObType::Fraction } else if ob_type == self.bytes { ObType::Bytes } else if ob_type == self.tuple {@@ -341,6 +346,8 @@ impl ObTypeLookup { ObType::MultiHostUrl } else if value.is_instance(self.decimal_object.bind(py)).unwrap_or(false) { ObType::Decimal+ } else if value.is_instance(self.fraction_object.bind(py)).unwrap_or(false) {+ ObType::Fraction } else if value.is_instance(self.uuid_object.bind(py)).unwrap_or(false) { ObType::Uuid } else if value.is_instance(self.enum_object.bind(py)).unwrap_or(false) {@@ -408,6 +415,7 @@ pub enum ObType { Float, FloatSubclass, Decimal,+ Fraction, // string types Str, StrSubclass,pydantic-core/src/serializers/shared.rsindex 694f3ecd2..81982159e 100644@@ -126,6 +126,7 @@ combined_serializer! { Bool: super::type_serializers::simple::BoolSerializer; Float: super::type_serializers::float::FloatSerializer; Decimal: super::type_serializers::decimal::DecimalSerializer;+ Fraction: super::type_serializers::fraction::FractionSerializer; Str: super::type_serializers::string::StrSerializer; Bytes: super::type_serializers::bytes::BytesSerializer; Datetime: super::type_serializers::datetime_etc::DatetimeSerializer;@@ -359,6 +360,7 @@ impl PyGcTraverse for CombinedSerializer { CombinedSerializer::Bool(inner) => inner.py_gc_traverse(visit), CombinedSerializer::Float(inner) => inner.py_gc_traverse(visit), CombinedSerializer::Decimal(inner) => inner.py_gc_traverse(visit),+ CombinedSerializer::Fraction(inner) => inner.py_gc_traverse(visit), CombinedSerializer::Str(inner) => inner.py_gc_traverse(visit), CombinedSerializer::Bytes(inner) => inner.py_gc_traverse(visit), CombinedSerializer::Datetime(inner) => inner.py_gc_traverse(visit),pydantic-core/src/serializers/type_serializers/fraction.rsnew file mode 100644index 000000000..cefadd83e@@ -0,0 +1,78 @@+use std::borrow::Cow;+use std::sync::{Arc, LazyLock};++use pyo3::prelude::*;+use pyo3::types::PyDict;++use crate::definitions::DefinitionsBuilder;+use crate::serializers::infer::{infer_json_key_known, infer_serialize_known, infer_to_python_known};+use crate::serializers::ob_type::{IsType, ObType};++use crate::serializers::SerializationState;++use super::{BuildSerializer, CombinedSerializer, TypeSerializer, infer_json_key, infer_serialize, infer_to_python};++#[derive(Debug)]+pub struct FractionSerializer {}++static FRACTION_SERIALIZER: LazyLock<Arc<CombinedSerializer>> =+ LazyLock::new(|| Arc::new(FractionSerializer {}.into()));++impl BuildSerializer for FractionSerializer {+ const EXPECTED_TYPE: &'static str = "fraction";++ fn build(+ _schema: &Bound<'_, PyDict>,+ _config: Option<&Bound<'_, PyDict>>,+ _definitions: &mut DefinitionsBuilder<Arc<CombinedSerializer>>,+ ) -> PyResult<Arc<CombinedSerializer>> {+ Ok(FRACTION_SERIALIZER.clone())+ }+}++impl_py_gc_traverse!(FractionSerializer {});++impl TypeSerializer for FractionSerializer {+ fn to_python<'py>(&self, value: &Bound<'py, PyAny>, state: &mut SerializationState<'py>) -> PyResult<Py<PyAny>> {+ match state.extra.ob_type_lookup.is_type(value, ObType::Fraction) {+ IsType::Exact | IsType::Subclass => infer_to_python_known(ObType::Fraction, value, state),+ IsType::False => {+ state.warn_fallback_py(self.get_name(), value)?;+ infer_to_python(value, state)+ }+ }+ }++ fn json_key<'a, 'py>(+ &self,+ key: &'a Bound<'py, PyAny>,+ state: &mut SerializationState<'py>,+ ) -> PyResult<Cow<'a, str>> {+ match state.extra.ob_type_lookup.is_type(key, ObType::Fraction) {+ IsType::Exact | IsType::Subclass => infer_json_key_known(ObType::Fraction, key, state),+ IsType::False => {+ state.warn_fallback_py(self.get_name(), key)?;+ infer_json_key(key, state)+ }+ }+ }++ fn serde_serialize<'py, S: serde::ser::Serializer>(+ &self,+ value: &Bound<'py, PyAny>,+ serializer: S,+ state: &mut SerializationState<'py>,+ ) -> Result<S::Ok, S::Error> {+ match state.extra.ob_type_lookup.is_type(value, ObType::Fraction) {+ IsType::Exact | IsType::Subclass => infer_serialize_known(ObType::Fraction, value, serializer, state),+ IsType::False => {+ state.warn_fallback_ser::<S>(self.get_name(), value)?;+ infer_serialize(value, serializer, state)+ }+ }+ }++ fn get_name(&self) -> &str {+ Self::EXPECTED_TYPE+ }+}pydantic-core/src/serializers/type_serializers/mod.rsindex f568d92f1..da95113ea 100644@@ -9,6 +9,7 @@ pub mod dict; pub mod enum_; pub mod float; pub mod format;+pub mod fraction; pub mod function; pub mod generator; pub mod json;pydantic-core/src/validators/fraction.rsnew file mode 100644index 000000000..795fd9586@@ -0,0 +1,168 @@+use std::sync::Arc;++use pyo3::exceptions::{PyOverflowError, PyTypeError, PyValueError, PyZeroDivisionError};+use pyo3::intern;+use pyo3::sync::PyOnceLock;+use pyo3::types::{IntoPyDict, PyDict, PyString, PyType};+use pyo3::{PyTypeInfo, prelude::*};++use crate::build_tools::is_strict;+use crate::errors::ErrorTypeDefaults;+use crate::errors::ValResult;+use crate::errors::{ErrorType, Number, ToErrorValue, ValError};+use crate::input::Input;++use super::{BuildValidator, CombinedValidator, DefinitionsBuilder, ValidationState, Validator};++static FRACTION_TYPE: PyOnceLock<Py<PyType>> = PyOnceLock::new();++pub fn get_fraction_type(py: Python<'_>) -> &Bound<'_, PyType> {+ FRACTION_TYPE+ .get_or_init(py, || {+ py.import("fractions")+ .and_then(|fraction_module| fraction_module.getattr("Fraction"))+ .unwrap()+ .extract()+ .unwrap()+ })+ .bind(py)+}++fn validate_as_fraction(+ py: Python,+ schema: &Bound<'_, PyDict>,+ key: &Bound<'_, PyString>,+) -> PyResult<Option<Py<PyAny>>> {+ match schema.get_item(key)? {+ Some(value) => match value.validate_fraction(false, py) {+ Ok(v) => Ok(Some(v.into_inner().unbind())),+ Err(_) => Err(PyValueError::new_err(format!(+ "'{key}' must be coercible to a Fraction instance",+ ))),+ },+ None => Ok(None),+ }+}++#[derive(Debug, Clone)]+pub struct FractionValidator {+ strict: bool,+ le: Option<Py<PyAny>>,+ lt: Option<Py<PyAny>>,+ ge: Option<Py<PyAny>>,+ gt: Option<Py<PyAny>>,+}++impl BuildValidator for FractionValidator {+ const EXPECTED_TYPE: &'static str = "fraction";+ fn build(+ schema: &Bound<'_, PyDict>,+ config: Option<&Bound<'_, PyDict>>,+ _definitions: &mut DefinitionsBuilder<Arc<CombinedValidator>>,+ ) -> PyResult<Arc<CombinedValidator>> {+ let py = schema.py();++ Ok(CombinedValidator::Fraction(Self {+ strict: is_strict(schema, config)?,+ le: validate_as_fraction(py, schema, intern!(py, "le"))?,+ lt: validate_as_fraction(py, schema, intern!(py, "lt"))?,+ ge: validate_as_fraction(py, schema, intern!(py, "ge"))?,+ gt: validate_as_fraction(py, schema, intern!(py, "gt"))?,+ })+ .into())+ }+}++impl_py_gc_traverse!(FractionValidator { le, lt, ge, gt });++impl Validator for FractionValidator {+ fn validate<'py>(+ &self,+ py: Python<'py>,+ input: &(impl Input<'py> + ?Sized),+ state: &mut ValidationState<'_, 'py>,+ ) -> ValResult<Py<PyAny>> {+ let fraction = input.validate_fraction(state.strict_or(self.strict), py)?.unpack(state);++ if let Some(le) = &self.le+ && !fraction.le(le)?+ {+ return Err(ValError::new(+ ErrorType::LessThanEqual {+ le: Number::String(le.to_string()),+ context: Some([("le", le)].into_py_dict(py)?.into()),+ },+ input,+ ));+ }+ if let Some(lt) = &self.lt+ && !fraction.lt(lt)?+ {+ return Err(ValError::new(+ ErrorType::LessThan {+ lt: Number::String(lt.to_string()),+ context: Some([("lt", lt)].into_py_dict(py)?.into()),+ },+ input,+ ));+ }+ if let Some(ge) = &self.ge+ && !fraction.ge(ge)?+ {+ return Err(ValError::new(+ ErrorType::GreaterThanEqual {+ ge: Number::String(ge.to_string()),+ context: Some([("ge", ge)].into_py_dict(py)?.into()),+ },+ input,+ ));+ }+ if let Some(gt) = &self.gt+ && !fraction.gt(gt)?+ {+ return Err(ValError::new(+ ErrorType::GreaterThan {+ gt: Number::String(gt.to_string()),+ context: Some([("gt", gt)].into_py_dict(py)?.into()),+ },+ input,+ ));+ }++ Ok(fraction.into())+ }++ fn get_name(&self) -> &str {+ Self::EXPECTED_TYPE+ }+}++pub(crate) fn create_fraction<'py>(arg: &Bound<'py, PyAny>, input: impl ToErrorValue) -> ValResult<Bound<'py, PyAny>> {+ let py = arg.py();+ get_fraction_type(py)+ .call1((arg,))+ .map_err(|e| handle_fraction_new_error(input, e))+}++fn handle_fraction_new_error(input: impl ToErrorValue, error: PyErr) -> ValError {+ Python::attach(|py| {+ if error.matches(py, PyTypeError::type_object(py)).unwrap_or(false) {+ ValError::new(ErrorTypeDefaults::FractionType, input)+ } else if error+ .matches(+ py,+ (+ PyValueError::type_object(py),+ PyZeroDivisionError::type_object(py),+ PyOverflowError::type_object(py),+ ),+ )+ .unwrap_or(false)+ {+ ValError::new(ErrorTypeDefaults::FractionParsing, input)+ } else {+ // Let other exceptions bubble up+ ValError::InternalErr(error)+ }+ })+}pydantic-core/src/validators/mod.rsindex 927abb0c4..68fa47288 100644@@ -39,6 +39,7 @@ mod definitions; mod dict; mod enum_; mod float;+pub(crate) mod fraction; mod frozenset; mod function; mod generator;@@ -586,6 +587,8 @@ fn build_validator_inner( float::FloatBuilder, // decimals decimal::DecimalValidator,+ // fractions+ fraction::FractionValidator, // tuples tuple::TupleValidator, // list/arrays@@ -749,6 +752,8 @@ pub enum CombinedValidator { ConstrainedFloat(float::ConstrainedFloatValidator), // decimals Decimal(decimal::DecimalValidator),+ // fractions+ Fraction(fraction::FractionValidator), // lists List(list::ListValidator), // sets - unique listspydantic-core/tests/test_errors.pyindex 541b1918e..ffddcb696 100644@@ -394,6 +394,8 @@ all_errors = [ ('uuid_version', 'UUID version 42 expected', {'expected_version': 42}), ('decimal_type', 'Decimal input should be an integer, float, string or Decimal object', None), ('decimal_parsing', 'Input should be a valid decimal', None),+ ('fraction_type', 'Fraction input should be an integer, float, string or Fraction object', None),+ ('fraction_parsing', 'Input is not a valid fraction', None), ('decimal_max_digits', 'Decimal input should have no more than 42 digits in total', {'max_digits': 42}), ('decimal_max_digits', 'Decimal input should have no more than 1 digit in total', {'max_digits': 1}), ('decimal_max_places', 'Decimal input should have no more than 42 decimal places', {'decimal_places': 42}),pydantic-core/tests/test_schema_functions.pyindex 4c6edfba1..299b08e3f 100644@@ -310,6 +310,7 @@ all_schema_functions = [ (core_schema.uuid_schema, args(), {'type': 'uuid'}), (core_schema.decimal_schema, args(), {'type': 'decimal'}), (core_schema.decimal_schema, args(multiple_of=5, gt=1.2), {'type': 'decimal', 'multiple_of': 5, 'gt': 1.2}),+ (core_schema.fraction_schema, args(), {'type': 'fraction'}), (core_schema.complex_schema, args(), {'type': 'complex'}), (core_schema.invalid_schema, args(), {'type': 'invalid'}), ]pydantic/_internal/_generate_schema.pyindex 637c3fc44..f20030b4b 100644@@ -640,23 +640,6 @@ class GenerateSchema: return schema - def _fraction_schema(self) -> CoreSchema:- """Support for [`fractions.Fraction`][fractions.Fraction]."""- from ._validators import fraction_validator-- # TODO: note, this is a fairly common pattern, re lax / strict for attempted type coercion,- # can we use a helper function to reduce boilerplate?- return core_schema.lax_or_strict_schema(- lax_schema=core_schema.no_info_plain_validator_function(fraction_validator),- strict_schema=core_schema.json_or_python_schema(- json_schema=core_schema.no_info_plain_validator_function(fraction_validator),- python_schema=core_schema.is_instance_schema(Fraction),- ),- # use str serialization to guarantee round trip behavior- serialization=core_schema.to_string_ser_schema(when_used='always'),- metadata={'pydantic_js_functions': [lambda _1, _2: {'type': 'string', 'format': 'fraction'}]},- )- def _arbitrary_type_schema(self, tp: Any) -> CoreSchema: if not isinstance(tp, type): warnings.warn(@@ -1083,7 +1066,7 @@ class GenerateSchema: elif obj is Url: return core_schema.url_schema() elif obj is Fraction:- return self._fraction_schema()+ return core_schema.fraction_schema() elif obj is MultiHostUrl: return core_schema.multi_host_url_schema() elif obj is None or obj is NoneType:pydantic/_internal/_known_annotated_metadata.pyindex 5954dba70..019568f5d 100644@@ -43,6 +43,7 @@ SEQUENCE_CONSTRAINTS = {*LENGTH_CONSTRAINTS, *FAIL_FAST} FLOAT_CONSTRAINTS = {*NUMERIC_CONSTRAINTS, *ALLOW_INF_NAN, *STRICT} DECIMAL_CONSTRAINTS = {'max_digits', 'decimal_places', *FLOAT_CONSTRAINTS}+FRACTION_CONSTRAINTS = {*INEQUALITY, *STRICT} INT_CONSTRAINTS = {*NUMERIC_CONSTRAINTS, *ALLOW_INF_NAN, *STRICT} BOOL_CONSTRAINTS = STRICT UUID_CONSTRAINTS = STRICT@@ -91,6 +92,7 @@ constraint_schema_pairings: list[tuple[set[str], tuple[str, ...]]] = [ (ENUM_CONSTRAINTS, ('enum',)), (DECIMAL_CONSTRAINTS, ('decimal',)), (COMPLEX_CONSTRAINTS, ('complex',)),+ (FRACTION_CONSTRAINTS, ('fraction',)), ] for constraints, schemas in constraint_schema_pairings:pydantic/_internal/_validators.pyindex a6baa54e6..602891452 100644@@ -11,7 +11,6 @@ import re import typing from collections.abc import Callable, Sequence from decimal import Decimal-from fractions import Fraction from ipaddress import IPv4Address, IPv4Interface, IPv4Network, IPv6Address, IPv6Interface, IPv6Network from typing import Any, TypeAlias, TypeVar, cast from zoneinfo import ZoneInfo, ZoneInfoNotFoundError@@ -246,16 +245,6 @@ def ip_v6_interface_validator(input_value: Any, /) -> IPv6Interface: raise PydanticCustomError('ip_v6_interface', 'Input is not a valid IPv6 interface') -def fraction_validator(input_value: Any, /) -> Fraction:- if isinstance(input_value, Fraction):- return input_value-- try:- return Fraction(input_value)- except ValueError:- raise PydanticCustomError('fraction_parsing', 'Input is not a valid fraction')-- def forbid_inf_nan_check(x: Any) -> Any: if not math.isfinite(x): raise PydanticKnownError('finite_number')pydantic/json_schema.pyindex 38a8ce235..612ec8ecf 100644@@ -683,6 +683,37 @@ class GenerateJsonSchema: json_schema = {k: v for k, v in json_schema.items() if v not in {math.inf, -math.inf}} return json_schema + def fraction_schema(self, schema: core_schema.FractionSchema) -> JsonSchemaValue:+ """Generates a JSON schema that matches a fraction value.++ Args:+ schema: The core schema.++ Returns:+ The generated JSON schema.++ """+ json_schema: JsonSchemaValue = {'type': 'string', 'format': 'fraction'}+ if self.mode == 'validation':+ le = schema.get('le')+ ge = schema.get('ge')+ lt = schema.get('lt')+ gt = schema.get('gt')+ json_schema = {+ 'anyOf': [+ self.float_schema(+ core_schema.float_schema(+ le=None if le is None else float(le),+ ge=None if ge is None else float(ge),+ lt=None if lt is None else float(lt),+ gt=None if gt is None else float(gt),+ )+ ),+ json_schema,+ ],+ }+ return json_schema+ def decimal_schema(self, schema: core_schema.DecimalSchema) -> JsonSchemaValue: """Generates a JSON schema that matches a decimal value. tests/test_types.pyindex 037533174..c899a3ba6 100644@@ -17,7 +17,6 @@ from dataclasses import dataclass from datetime import date, datetime, time, timedelta, timezone from decimal import Decimal from enum import Enum, IntEnum-from fractions import Fraction from numbers import Number from pathlib import Path from re import Pattern@@ -1883,17 +1882,6 @@ def test_invalid_schema_constraints(kwargs, type_, a): Foo(a=a) -def test_fraction_validation():- class Model(BaseModel):- a: Fraction-- with pytest.raises(ValidationError) as exc_info:- Model(a='wrong_format')- assert exc_info.value.errors(include_url=False) == [- {'type': 'fraction_parsing', 'loc': ('a',), 'msg': 'Input is not a valid fraction', 'input': 'wrong_format'}- ]-- @pytest.mark.skipif(not email_validator, reason='email_validator not installed') def test_string_success(): class MoreStringsModel(BaseModel):@@ -7155,35 +7143,6 @@ def test_ser_ip_python_and_json() -> None: assert ta.dump_json(ip) == b'"127.0.0.1"' -@pytest.mark.parametrize('input_data', ['1/3', 1.333, Fraction(1, 3), Decimal('1.333')])-def test_fraction_validation_lax(input_data) -> None:- ta = TypeAdapter(Fraction)- fraction = ta.validate_python(input_data)- assert isinstance(fraction, Fraction)---def test_fraction_validation_strict() -> None:- ta = TypeAdapter(Fraction, config=ConfigDict(strict=True))-- assert ta.validate_python(Fraction(1 / 3)) == Fraction(1 / 3)-- # only fractions accepted in strict mode- for lax_fraction in ['1/3', 1.333, Decimal('1.333')]:- with pytest.raises(ValidationError):- ta.validate_python(lax_fraction)---def test_fraction_serialization() -> None:- ta = TypeAdapter(Fraction)- assert ta.dump_python(Fraction(1, 3)) == '1/3'- assert ta.dump_json(Fraction(1, 3)) == b'"1/3"'---def test_fraction_json_schema() -> None:- ta = TypeAdapter(Fraction)- assert ta.json_schema() == {'type': 'string', 'format': 'fraction'}-- def test_annotated_metadata_any_order() -> None: def validator(v): if isinstance(v, (int, float)):tests/types/test_fraction.pyindex bb5b6ee12..81bd4ab25 100644@@ -1,10 +1,11 @@+from decimal import Decimal from fractions import Fraction from typing import Annotated import annotated_types import pytest -from pydantic import BaseModel, ConfigDict, TypeAdapter, ValidationError+from pydantic import Field, TypeAdapter, ValidationError class FractionSubclass(Fraction):@@ -21,6 +22,7 @@ class FractionSubclass(Fraction): ('42.123', Fraction('42.123')), (42.0, Fraction(42)), (42.5, Fraction('42.5')),+ (Decimal('1.333'), Fraction('1.333')), (1e10, Fraction('1E10')), (Fraction('42.0'), Fraction(42)), (Fraction('42.5'), Fraction('42.5')),@@ -41,12 +43,6 @@ class FractionSubclass(Fraction): ], ) def test_fraction(input_value, expected):- class Model(BaseModel):- v: Fraction-- m = Model(v=input_value)- assert m.v == expected- ta = TypeAdapter(Fraction) assert ta.validate_python(input_value) == expected @@ -68,11 +64,28 @@ def test_fraction_validate_json(json_str, expected): assert ta.validate_json(json_str) == expected +@pytest.mark.parametrize(+ 'str,expected',+ [+ ('1/3', Fraction(1, 3)),+ ('42.5', Fraction('42.5')),+ ('0', Fraction(0)),+ ('42', Fraction(42)),+ ('42.5', Fraction('42.5')),+ ('0/100', Fraction(0)),+ ('-47e-2', Fraction(-47, 100)),+ ],+)+def test_fraction_validate_strings(str, expected):+ ta = TypeAdapter(Fraction)+ assert ta.validate_strings(str) == expected++ @pytest.mark.parametrize( 'json_str,error', [ ('"not a number"', ValidationError),- ('"1/0"', ZeroDivisionError),+ ('"1/0"', ValidationError), (float('inf'), ValidationError), (float('nan'), ValidationError), ],@@ -91,19 +104,14 @@ def test_fraction_validate_json_error(json_str, error): (False), ('not a number'), ('1/0'),+ ('1/3'),+ (1.333),+ (Decimal('1.333')), (float('inf')), (float('nan')), ], ) def test_fraction_validation_error_strict(input_value):- class Model(BaseModel):- v: Fraction-- model_config = ConfigDict(strict=True)-- with pytest.raises(ValidationError):- Model(v=input_value)- with pytest.raises(ValidationError): ta = TypeAdapter(Fraction) ta.validate_python(input_value, strict=True)@@ -124,21 +132,21 @@ def test_fraction_strict_accepts_fraction(input_value): @pytest.mark.parametrize(- 'input_value,error',+ ['input', 'error_type'], [- ('not a number', ValidationError),- ('1/0', ZeroDivisionError),- (float('inf'), OverflowError),- (float('nan'), ValidationError),- ([1, 2], TypeError),- ({}, TypeError),- (None, TypeError),+ ('wrong_format', 'fraction_parsing'), # Raises `ValueError` internally+ ('1/0', 'fraction_parsing'), # Raises `ZeroDivisionError` internally+ (float('inf'), 'fraction_parsing'), # Raises `OverflowError` internally+ (float('nan'), 'fraction_parsing'), # Raises `ValueError` internally+ (type, 'fraction_type'), # Raises `TypeError` internally ], )-def test_fraction_validation_error_non_strict(input_value, error):- with pytest.raises(error):- ta = TypeAdapter(Fraction)- ta.validate_python(input_value, strict=False)+def test_fraction_validation_error(input: object, error_type: str):++ ta = TypeAdapter(Fraction)++ with pytest.raises(ValidationError, check=lambda e: e.errors()[0]['type'] == error_type):+ ta.validate_python(input) @pytest.mark.parametrize(@@ -212,4 +220,8 @@ def test_fraction_constraints_error(constraint, input_value): def test_fraction_json_schema(): ta = TypeAdapter(Fraction)- assert ta.json_schema() == {'type': 'string', 'format': 'fraction'}+ assert ta.json_schema(mode='serialization') == {'type': 'string', 'format': 'fraction'}++ ta = TypeAdapter(Annotated[Fraction, Field(ge=Fraction(1))])++ assert ta.json_schema() == {'anyOf': [{'minimum': 1.0, 'type': 'number'}, {'format': 'fraction', 'type': 'string'}]}