Skip to content

Commit

Permalink
Refactor: navigate code back towards 0.6.2.12 baseline
Browse files Browse the repository at this point in the history
  • Loading branch information
jayaddison committed Dec 15, 2024
1 parent 580af7b commit 59d5146
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 9 deletions.
17 changes: 10 additions & 7 deletions src/timedelta_isoformat/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -87,23 +87,22 @@ def _parse(duration: Iterator[str], context: Iterator[str] | None = None) -> Com
in order of largest-to-smallest unit from left-to-right (with the exception of
week measurements, which must be the only measurement in the string if present).
"""
parser = timedelta._parse_date if not context else timedelta._parse_time
context = context or iter(("Y", "years", "M", "months", "D", "days"))
date_context = iter(("Y", "years", "M", "months", "D", "days"))

accumulator, unit = "", None
context, accumulator, unit = context or date_context, "", None
for char in duration:
if char in {",", "-", ".", "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", ":"}:
accumulator += "." if char == "," else char
continue

if char == "T" and parser is timedelta._parse_date:
if char == "T" and context is date_context:
time_context = iter(("H", "hours", "M", "minutes", "S", "seconds"))
yield from timedelta._parse(duration, context=time_context)
break

if char == "W" and parser is timedelta._parse_date:
if char == "W":
assert not unit, "cannot mix weeks with other units"
parser, context = None, iter(("W", "weeks"))
context = iter(("W", "weeks"))
pass

if char not in context:
Expand All @@ -112,7 +111,11 @@ def _parse(duration: Iterator[str], context: Iterator[str] | None = None) -> Com
value, unit, accumulator = accumulator, next(context), ""
yield value, unit, None, False

assert not accumulator or not unit, f"missing unit designator after '{accumulator}'"
if not accumulator:
return

assert not unit, f"missing unit designator after '{accumulator}'"
parser = timedelta._parse_date if context is date_context else timedelta._parse_time
yield from parser(accumulator) if accumulator else ()

@staticmethod
Expand Down
4 changes: 2 additions & 2 deletions tests/test_timedelta_isoformat.py
Original file line number Diff line number Diff line change
Expand Up @@ -100,9 +100,9 @@
("P0000-0.0", "unable to parse '0.0' as a positive number"),
# segment repetition
("PT5MT5S", "unexpected character 'T'"),
("P1W2W", "unexpected character 'W'"),
("P1W2W", "cannot mix weeks with other units"),
# segments out-of-order
("P1DT5S2W", "unexpected character 'W'"),
("P1DT5S2W", "cannot mix weeks with other units"),
("P1W1D", "unexpected character 'D'"),
# unexpected characters within date/time components
("PT01:-2:03", "unable to parse '-2' as a positive number"),
Expand Down

0 comments on commit 59d5146

Please sign in to comment.