Negotiation & names¶
Choose the closest supported locale for a user and build alphabetical indexes for contact lists.
| Method | Use it for |
|---|---|
best_match(supported) |
Choose the closest supported locale |
from_accept_language(header, supported) |
Negotiate from an HTTP header |
index_buckets(names) |
Build alphabetical section headers |
Best-match locale negotiation¶
from_accept_language(header) alone just parses the header and picks the
highest-quality tag. Passing your supported locales enables CLDR
language-distance matching. This chooses the
closest supported locale, falling back to the first entry when none is close.
# Which of MY locales best serves this user?
Cosmo("en_AU").best_match(["en-US", "en-GB", "fr"]) # "en-GB" (closer than en-US)
Cosmo("ja").best_match(["fr", "de"]) # "fr" (fallback: first)
# Negotiate straight from an Accept-Language header:
c = Cosmo.from_accept_language("fr-CH, en;q=0.9", supported=["en-US", "fr-FR"])
c.locale # "fr_FR"
Cosmo.from_accept_language("", supported=["en-US", "fr-FR"]).locale # "en_US"
Why language distance beats prefix matching: en_AU is served better by en-GB
than en-US (closer English variant); sr-Latn maps to hr over sr-Cyrl
(shared script wins); nn (Nynorsk) falls back to nb (Bokmål). These matches use language and script relationships that prefix matching cannot
express. An empty supported list throws.
Order your supported list by preference
The first entry is the fallback when nothing matches, so put your default locale first. Everything after it is reachable only when it's genuinely the closest.
Alphabetical index buckets¶
index_buckets(names) groups strings under the locale's index headers — A–Z in
English, but 가나다 in Korean, あかさ in Japanese, А–Я in Russian — with each bucket
collation-ordered. These are the section headers you'd run down the side of a
contact list. Empty buckets are omitted.
buckets = Cosmo("en").index_buckets(["banana", "apple", "Cherry", "avocado"])
list(buckets) # ["A", "B", "C"]
buckets["A"] # ["apple", "avocado"]
The buckets come back in index order (an ordered map / LinkedHashMap), so you
can iterate straight into your UI without re-sorting. Names that don't fit any
letter bucket land in an overflow bucket (often #).
Practical examples¶
An HTTP request handler that picks the right locale. Negotiate once, then build every formatter from the chosen locale:
SUPPORTED = ["en-US", "fr-FR", "de-DE", "ja-JP"] # first = default
def handle(request):
header = request.headers.get("Accept-Language", "")
c = Cosmo.from_accept_language(header, supported=SUPPORTED)
return render(greeting=c.message("Welcome to {app}", {"app": "Acme"}),
lang=c.locale, direction=c.direction())
A jump-list contact index. Feed the display names to index_buckets() and render
each key as a sticky header: