Skip to content

Commit d2b66b9

Browse files
committed
gh-152060: Fix datetime.fromisoformat() raising AssertionError in pure Python
_pydatetime._parse_isoformat_date() asserted the date portion length, leaking a bare AssertionError out of datetime.fromisoformat() for some malformed strings (e.g. '2020-2020'), and behaving differently under -O. The C accelerator already raises ValueError. Replace the assert with an explicit ValueError so both implementations agree on all builds.
1 parent a46db4f commit d2b66b9

3 files changed

Lines changed: 7 additions & 1 deletion

File tree

Lib/_pydatetime.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -358,7 +358,8 @@ def _find_isoformat_datetime_separator(dtstr):
358358
def _parse_isoformat_date(dtstr):
359359
# It is assumed that this is an ASCII-only string of lengths 7, 8 or 10,
360360
# see the comment on Modules/_datetimemodule.c:_find_isoformat_datetime_separator
361-
assert len(dtstr) in (7, 8, 10)
361+
if len(dtstr) not in (7, 8, 10):
362+
raise ValueError(f"Invalid isoformat string: {dtstr!r}")
362363
year = int(dtstr[0:4])
363364
has_sep = dtstr[4] == '-'
364365

Lib/test/datetimetester.py

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3757,6 +3757,8 @@ def test_fromisoformat_fails_datetime(self):
37573757
'2009-04-19T12:30:45+00:00:90', # Time zone field out from range
37583758
'2009-04-19T12:30:45-00:90:00', # Time zone field out from range
37593759
'2009-04-19T12:30:45-00:00:90', # Time zone field out from range
3760+
'2020-2020', # Ambiguous 9-char date portion
3761+
'2020-1234', # Ambiguous 9-char date portion
37603762
]
37613763

37623764
for bad_str in bad_strs:
Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
Fix :meth:`datetime.datetime.fromisoformat` raising :exc:`AssertionError`
2+
instead of :exc:`ValueError` for some malformed strings in the pure-Python
3+
implementation, matching the C implementation.

0 commit comments

Comments
 (0)