Skip to content

Commit 32e6561

Browse files
authored
Cache validity of a locale name
Currently `_cache` is only populated on `load`, this is an issue with code which do a lot of locale parsing / instantiation but for one reason or an other rarely end up needing to actually load the locale data (e.g. date formatting with non-locale-dependent patterns) because every cache miss is an `os.path.exists`. This change takes advantage of semantics differences between `exists` and `load`: `exists` just needs the entry to exist in the cache, while `load` needs the entry to be truthy. Thus `exists` can cache its lookup by setting an empty dict (or even `None` but that seems a bit too dodgy). Alternatively we could remove the `os.path.exists` "slow path" and call `normalize_locale` every time, as `locale_identifiers` gets cached on first call, the initial call would be a lot more expensive but then no further `exists` would need to touch the filesystem. For a third alternative, `exists` could be decorated with `functools.cache`, in order to have its own cache completely independent of `load`. `load` could also be migrated to `functools.cache` as, as far as I can tell, the `localedata._cache` is never invalidated anyway, with the drawback that a locale's data might be resolved multiple times if concurrent calls are tight enough (`functools.cache` synchronises the cache but not the resolution of the value).
1 parent 56c63ca commit 32e6561

File tree

1 file changed

+4
-1
lines changed

1 file changed

+4
-1
lines changed

babel/localedata.py

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -72,7 +72,10 @@ def exists(name: str) -> bool:
7272
if name in _cache:
7373
return True
7474
file_found = os.path.exists(resolve_locale_filename(name))
75-
return True if file_found else bool(normalize_locale(name))
75+
if file_found or normalize_locale(name):
76+
_cache.setdefault(name, {})
77+
return True
78+
return False
7679

7780

7881
@lru_cache(maxsize=None)

0 commit comments

Comments
 (0)