From 01b3968f9ec6d0bb0797f662586aa2998e3e3a89 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Miroslav=20=C5=A0ediv=C3=BD?= <6774676+eumiro@users.noreply.github.com> Date: Wed, 23 Apr 2025 17:46:03 +0200 Subject: [PATCH] Optimize usage of re. methods --- src/pendulum/formatting/formatter.py | 5 ++--- src/pendulum/locales/locale.py | 2 +- src/pendulum/parsing/__init__.py | 2 +- src/pendulum/parsing/iso8601.py | 4 ++-- 4 files changed, 6 insertions(+), 7 deletions(-) diff --git a/src/pendulum/formatting/formatter.py b/src/pendulum/formatting/formatter.py index da05617d..51c90128 100644 --- a/src/pendulum/formatting/formatter.py +++ b/src/pendulum/formatting/formatter.py @@ -377,8 +377,7 @@ def parse( """ escaped_fmt = re.escape(fmt) - tokens = self._FROM_FORMAT_RE.findall(escaped_fmt) - if not tokens: + if not self._FROM_FORMAT_RE.search(escaped_fmt): raise ValueError("The given time string does not match the given format") if not locale: @@ -406,7 +405,7 @@ def parse( lambda m: self._replace_tokens(m.group(0), loaded_locale), escaped_fmt ) - if not re.search("^" + pattern + "$", time): + if not re.fullmatch(pattern, time): raise ValueError(f"String does not match format {fmt}") def _get_parsed_values(m: Match[str]) -> Any: diff --git a/src/pendulum/locales/locale.py b/src/pendulum/locales/locale.py index 12b87f81..d396ecbc 100644 --- a/src/pendulum/locales/locale.py +++ b/src/pendulum/locales/locale.py @@ -48,7 +48,7 @@ def load(cls, locale: str | Locale) -> Locale: @classmethod def normalize_locale(cls, locale: str) -> str: - m = re.match("([a-z]{2})[-_]([a-z]{2})", locale, re.I) + m = re.fullmatch("([a-z]{2})[-_]([a-z]{2})", locale, re.I) if m: return f"{m.group(1).lower()}_{m.group(2).lower()}" else: diff --git a/src/pendulum/parsing/__init__.py b/src/pendulum/parsing/__init__.py index a7bad31d..4ad27efe 100644 --- a/src/pendulum/parsing/__init__.py +++ b/src/pendulum/parsing/__init__.py @@ -140,7 +140,7 @@ def _parse_common(text: str, **options: Any) -> datetime | date | time: :param text: The string to parse. """ - m = COMMON.match(text) + m = COMMON.fullmatch(text) has_date = False year = 0 month = 1 diff --git a/src/pendulum/parsing/iso8601.py b/src/pendulum/parsing/iso8601.py index 101eb3b3..908cdc75 100644 --- a/src/pendulum/parsing/iso8601.py +++ b/src/pendulum/parsing/iso8601.py @@ -97,7 +97,7 @@ def parse_iso8601( if parsed is not None: return parsed - m = ISO8601_DT.match(text) + m = ISO8601_DT.fullmatch(text) if not m: raise ParserError("Invalid ISO 8601 string") @@ -264,7 +264,7 @@ def parse_iso8601( def _parse_iso8601_duration(text: str, **options: str) -> Duration | None: - m = ISO8601_DURATION.match(text) + m = ISO8601_DURATION.fullmatch(text) if not m: return None