Skip to content

Commit

Permalink
Replace babel.dates._pattern_cache with an LRU cache
Browse files Browse the repository at this point in the history
Fixes #962
  • Loading branch information
akx committed Feb 7, 2023
1 parent 14e7c00 commit 221c937
Showing 1 changed file with 6 additions and 8 deletions.
14 changes: 6 additions & 8 deletions babel/dates.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@

import re
import warnings
from functools import lru_cache
from typing import TYPE_CHECKING, SupportsInt

try:
Expand Down Expand Up @@ -1667,10 +1668,8 @@ def get_week_number(self, day_of_period: int, day_of_week: int | None = None) ->
#: in order of decreasing magnitude.
PATTERN_CHAR_ORDER = "GyYuUQqMLlwWdDFgEecabBChHKkjJmsSAzZOvVXx"

_pattern_cache = {}


def parse_pattern(pattern: str) -> DateTimePattern:
def parse_pattern(pattern: str | DateTimePattern) -> DateTimePattern:
"""Parse date, time, and datetime format patterns.
>>> parse_pattern("MMMMd").format
Expand All @@ -1693,10 +1692,11 @@ def parse_pattern(pattern: str) -> DateTimePattern:
"""
if isinstance(pattern, DateTimePattern):
return pattern
return _cached_parse_pattern(pattern)

if pattern in _pattern_cache:
return _pattern_cache[pattern]

@lru_cache(maxsize=1024)
def _cached_parse_pattern(pattern: str) -> DateTimePattern:
result = []

for tok_type, tok_value in tokenize_pattern(pattern):
Expand All @@ -1710,9 +1710,7 @@ def parse_pattern(pattern: str) -> DateTimePattern:
result.append('%%(%s)s' % (fieldchar * fieldnum))
else:
raise NotImplementedError(f"Unknown token type: {tok_type}")

_pattern_cache[pattern] = pat = DateTimePattern(pattern, ''.join(result))
return pat
return DateTimePattern(pattern, ''.join(result))


def tokenize_pattern(pattern: str) -> list[tuple[str, str | tuple[str, int]]]:
Expand Down

0 comments on commit 221c937

Please sign in to comment.