Skip to content

Commit 6588871

Browse files
committed
Optimize usage of re. methods
1 parent 91d0c1e commit 6588871

File tree

4 files changed

+14
-33
lines changed

4 files changed

+14
-33
lines changed

src/pendulum/formatting/formatter.py

+10-29
Original file line numberDiff line numberDiff line change
@@ -68,17 +68,13 @@ class Formatter:
6868

6969
_FROM_FORMAT_RE: re.Pattern[str] = re.compile(r"(?<!\\\[)" + _TOKENS + r"(?!\\\])")
7070

71-
_LOCALIZABLE_TOKENS: ClassVar[
72-
dict[str, str | Callable[[Locale], Sequence[str]] | None]
73-
] = {
71+
_LOCALIZABLE_TOKENS: ClassVar[dict[str, str | Callable[[Locale], Sequence[str]] | None]] = {
7472
"Qo": None,
7573
"MMMM": "months.wide",
7674
"MMM": "months.abbreviated",
7775
"Mo": None,
7876
"DDDo": None,
79-
"Do": lambda locale: tuple(
80-
rf"\d+{o}" for o in locale.get("custom.ordinal").values()
81-
),
77+
"Do": lambda locale: tuple(rf"\d+{o}" for o in locale.get("custom.ordinal").values()),
8278
"dddd": "days.wide",
8379
"ddd": "days.abbreviated",
8480
"dd": "days.short",
@@ -242,9 +238,7 @@ class Formatter:
242238
"z": str,
243239
}
244240

245-
def format(
246-
self, dt: pendulum.DateTime, fmt: str, locale: str | Locale | None = None
247-
) -> str:
241+
def format(self, dt: pendulum.DateTime, fmt: str, locale: str | Locale | None = None) -> str:
248242
"""
249243
Formats a DateTime instance with a given format and locale.
250244
@@ -303,9 +297,7 @@ def _format_token(self, dt: pendulum.DateTime, token: str, locale: Locale) -> st
303297

304298
return token
305299

306-
def _format_localizable_token(
307-
self, dt: pendulum.DateTime, token: str, locale: Locale
308-
) -> str:
300+
def _format_localizable_token(self, dt: pendulum.DateTime, token: str, locale: Locale) -> str:
309301
"""
310302
Formats a DateTime instance
311303
with a given localizable token and locale.
@@ -377,8 +369,7 @@ def parse(
377369
"""
378370
escaped_fmt = re.escape(fmt)
379371

380-
tokens = self._FROM_FORMAT_RE.findall(escaped_fmt)
381-
if not tokens:
372+
if not self._FROM_FORMAT_RE.search(escaped_fmt):
382373
raise ValueError("The given time string does not match the given format")
383374

384375
if not locale:
@@ -402,11 +393,9 @@ def parse(
402393
"timestamp": None,
403394
}
404395

405-
pattern = self._FROM_FORMAT_RE.sub(
406-
lambda m: self._replace_tokens(m.group(0), loaded_locale), escaped_fmt
407-
)
396+
pattern = self._FROM_FORMAT_RE.sub(lambda m: self._replace_tokens(m.group(0), loaded_locale), escaped_fmt)
408397

409-
if not re.search("^" + pattern + "$", time):
398+
if not re.fullmatch(pattern, time):
410399
raise ValueError(f"String does not match format {fmt}")
411400

412401
def _get_parsed_values(m: Match[str]) -> Any:
@@ -416,9 +405,7 @@ def _get_parsed_values(m: Match[str]) -> Any:
416405

417406
return self._check_parsed(parsed, now)
418407

419-
def _check_parsed(
420-
self, parsed: dict[str, Any], now: pendulum.DateTime
421-
) -> dict[str, Any]:
408+
def _check_parsed(self, parsed: dict[str, Any], now: pendulum.DateTime) -> dict[str, Any]:
422409
"""
423410
Checks validity of parsed elements.
424411
@@ -619,9 +606,7 @@ def _get_parsed_value(
619606

620607
parsed["tz"] = pendulum.timezone(value)
621608

622-
def _get_parsed_locale_value(
623-
self, token: str, value: str, parsed: dict[str, Any], locale: Locale
624-
) -> None:
609+
def _get_parsed_locale_value(self, token: str, value: str, parsed: dict[str, Any], locale: Locale) -> None:
625610
if token == "MMMM":
626611
unit = "month"
627612
match = "months.wide"
@@ -680,11 +665,7 @@ def _replace_tokens(self, token: str, locale: Locale) -> str:
680665
if callable(values):
681666
candidates = values(locale)
682667
else:
683-
candidates = tuple(
684-
locale.translation(
685-
cast("str", self._LOCALIZABLE_TOKENS[token])
686-
).values()
687-
)
668+
candidates = tuple(locale.translation(cast("str", self._LOCALIZABLE_TOKENS[token])).values())
688669
else:
689670
candidates = cast("Sequence[str]", self._REGEX_TOKENS[token])
690671

src/pendulum/locales/locale.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -48,7 +48,7 @@ def load(cls, locale: str | Locale) -> Locale:
4848

4949
@classmethod
5050
def normalize_locale(cls, locale: str) -> str:
51-
m = re.match("([a-z]{2})[-_]([a-z]{2})", locale, re.I)
51+
m = re.fullmatch("([a-z]{2})[-_]([a-z]{2})", locale, re.I)
5252
if m:
5353
return f"{m.group(1).lower()}_{m.group(2).lower()}"
5454
else:

src/pendulum/parsing/__init__.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -140,7 +140,7 @@ def _parse_common(text: str, **options: Any) -> datetime | date | time:
140140
141141
:param text: The string to parse.
142142
"""
143-
m = COMMON.match(text)
143+
m = COMMON.fullmatch(text)
144144
has_date = False
145145
year = 0
146146
month = 1

src/pendulum/parsing/iso8601.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -97,7 +97,7 @@ def parse_iso8601(
9797
if parsed is not None:
9898
return parsed
9999

100-
m = ISO8601_DT.match(text)
100+
m = ISO8601_DT.fullmatch(text)
101101
if not m:
102102
raise ParserError("Invalid ISO 8601 string")
103103

@@ -264,7 +264,7 @@ def parse_iso8601(
264264

265265

266266
def _parse_iso8601_duration(text: str, **options: str) -> Duration | None:
267-
m = ISO8601_DURATION.match(text)
267+
m = ISO8601_DURATION.fullmatch(text)
268268
if not m:
269269
return None
270270

0 commit comments

Comments
 (0)