Skip to content

Commit

Permalink
refactor: make date parser use internal int parser
Browse files Browse the repository at this point in the history
  • Loading branch information
Sharp-Eyes committed Sep 19, 2024
1 parent 31b6282 commit a963230
Showing 1 changed file with 45 additions and 5 deletions.
50 changes: 45 additions & 5 deletions src/disnake/ext/components/impl/parser/stdlib.py
Original file line number Diff line number Diff line change
Expand Up @@ -437,6 +437,7 @@ class DatetimeParser(parser_base.Parser[datetime.datetime]):
Defaults to ``True``.
int_parser:
The :class:`IntParser` to use internally for this parser.
"""

resolution: int | float
Expand Down Expand Up @@ -558,12 +559,51 @@ def dumps(self, argument: datetime.datetime) -> str:


@parser_base.register_parser_for(datetime.date)
class DateParser(parser_base.Parser[datetime.date]): # noqa: D101
def loads(self, argument: str) -> datetime.date: # noqa: D102
return datetime.date.fromordinal(int(argument))
class DateParser(parser_base.Parser[datetime.date]):
"""Parser type with support for dates.
Parameters
----------
int_parser:
The :class:`IntParser` to use internally for this parser.
"""

int_parser: IntParser
"""The :class:`IntParser` to use internally for this parser.
Since the default integer parser uses base-36 to "compress" numbers, the
default date parser will also return compressed results.
"""

def dumps(self, argument: datetime.date) -> str: # noqa: D102
return str(datetime.date.toordinal(argument))
def __init__(self, *, int_parser: typing.Optional[IntParser]):
self.int_parser = int_parser or IntParser.default()

def loads(self, argument: str) -> datetime.date:
"""Load a date from a string.
This uses the underlying :attr:`int_parser`.
Parameters
----------
argument:
The string that is to be converted into a date.
"""
return datetime.date.fromordinal(self.int_parser.loads(argument))

def dumps(self, argument: datetime.date) -> str:
"""Dump a datetime into a string.
This uses the underlying :attr:`int_parser`.
Parameters
----------
argument:
The value that is to be dumped.
"""
return self.int_parser.dumps(datetime.date.toordinal(argument))


@parser_base.register_parser_for(datetime.time)
Expand Down

0 comments on commit a963230

Please sign in to comment.