10BC0 Trimming str before parsing to int and float by hungtsetse · Pull Request #1203 · pydantic/pydantic-core · GitHub
[go: up one dir, main page]

Skip to content
Merged
Show file tree
Hide file tree
Changes from all 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
3 changes: 2 additions & 1 deletion src/input/shared.rs
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,7 @@ fn strip_underscores(s: &str) -> Option<String> {
/// https://docs.python.org/3/whatsnew/3.11.html#other-cpython-implementation-changes and
/// https://github.com/python/cpython/issues/95778 for more info in that length bound
pub fn str_as_int<'s, 'l>(input: &'s impl Input<'s>, str: &'l str) -> ValResult<EitherInt<'s>> {
let str = str.trim();
let len = str.len();
if len > 4300 {
Err(ValError::new(ErrorTypeDefaults::IntParsingSize, input))
Expand All @@ -96,7 +97,7 @@ pub fn str_as_int<'s, 'l>(input: &'s impl Input<'s>, str: &'l str) -> ValResult<

/// parse a float as a float
pub fn str_as_float<'s, 'l>(input: &'s impl Input<'s>, str: &'l str) -> ValResult<EitherFloat<'s>> {
match str.parse() {
match str.trim().parse() {
Ok(float) => Ok(EitherFloat::F64(float)),
Err(_) => match strip_underscores(str).and_then(|stripped| stripped.parse().ok()) {
Some(float) => Ok(EitherFloat::F64(float)),
Expand Down
1 change: 1 addition & 0 deletions tests/validators/test_float.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@
(1, 1),
(42, 42),
('42', 42),
(' 42.1 ', 42.1),
('42.123', 42.123),
(42.0, 42),
(42.5, 42.5),
Expand Down
1 change: 1 addition & 0 deletions tests/validators/test_int.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@
(0, 0),
('0', 0),
(1, 1),
(' 1 ', 1),
(42, 42),
('42', 42),
(42.0, 42),
Expand Down
0