From e8c1fb63abe4d94ded52d373c81451aa7258509f Mon Sep 17 00:00:00 2001 From: Christian Ledermann Date: Thu, 14 Nov 2024 12:42:15 +0000 Subject: [PATCH] refactor KmlDateTime class and add get_all_attrs utility function --- fastkml/times.py | 8 +++----- fastkml/utils.py | 40 +++++++++++++++++++++++++++++----------- tox.ini | 1 - 3 files changed, 32 insertions(+), 17 deletions(-) diff --git a/fastkml/times.py b/fastkml/times.py index 093902df..a2f35b5f 100644 --- a/fastkml/times.py +++ b/fastkml/times.py @@ -45,7 +45,7 @@ # regular expression to parse a gYearMonth string # year and month may be separated by an optional dash -# year is always 4 digits, month is always 2 digits +# year is always 4 digits, month, day is always 2 digits year_month_day = re.compile( r"^(?P\d{4})(?:-)?(?P\d{2})?(?:-)?(?P\d{2})?$", ) @@ -205,10 +205,8 @@ def parse(cls, datestr: str) -> Optional["KmlDateTime"]: resolution = DateTimeResolution.year_month if year_month_day_match.group("month") is None: resolution = DateTimeResolution.year - elif len(datestr) > 10: # noqa: PLR2004 - dt = arrow.get(datestr).datetime - resolution = DateTimeResolution.datetime - return cls(dt, resolution) if dt else None + return cls(dt, resolution) + return cls(arrow.get(datestr).datetime, DateTimeResolution.datetime) @classmethod def get_ns_id(cls) -> str: diff --git a/fastkml/utils.py b/fastkml/utils.py index 87cc7d38..9f3bc0f7 100644 --- a/fastkml/utils.py +++ b/fastkml/utils.py @@ -30,6 +30,32 @@ def has_attribute_values(obj: object, **kwargs: Any) -> bool: return False +def get_all_attrs(obj: object) -> Generator[object, None, None]: + """ + Get all attributes of an object. + + Args: + ---- + obj: The object to get attributes from. + + Returns: + ------- + An iterable of all attributes of the object or, if the attribute itself is + iterable, iterate over the attribute values. + + """ + try: + attrs = (attr for attr in obj.__dict__ if not attr.startswith("_")) + except AttributeError: + return + for attr_name in attrs: + attr = getattr(obj, attr_name) + try: + yield from attr + except TypeError: + yield attr + + def find_all( obj: object, *, @@ -55,17 +81,9 @@ def find_all( **kwargs, ): yield obj - try: - attrs = (attr for attr in obj.__dict__ if not attr.startswith("_")) - except AttributeError: - return - for attr_name in attrs: - attr = getattr(obj, attr_name) - try: - for item in attr: - yield from find_all(item, of_type=of_type, **kwargs) - except TypeError: - yield from find_all(attr, of_type=of_type, **kwargs) + + for attr in get_all_attrs(obj): + yield from find_all(attr, of_type=of_type, **kwargs) def find( diff --git a/tox.ini b/tox.ini index 3456d188..4fb8dc1a 100644 --- a/tox.ini +++ b/tox.ini @@ -9,7 +9,6 @@ per-file-ignores = examples/*.py: DALL fastkml/gx.py: LIT002 fastkml/views.py: LIT002 - fastkml/utils.py: CCR001 fastkml/registry.py: E704 docs/conf.py: E402 enable-extensions=G