892b8a1c80acb807a976077ae64f6bcd95c03025
[python-collate.git] / collate / icu / __init__.py
1 """ICU-based collation.
2
3 This collation backend uses the International Components for Unicode
4 library to provide accurate and high-performance collation. It
5 supports multiple locales and advanced sorting capabilities.
6
7 Use this collation backend if possible; it's by far the best.
8
9 Avoid this backend if...
10 - ICU is not available for your system.
11
12 """
13
14 import collate._abcollator
15 import collate._locale
16 import collate.errors
17
18 from collate.icu import _icu
19
20 class Collator(collate._abcollator.Collator):
21 """ICU-based collation."""
22
23 def __init__(self, locale, encoding=None):
24 locale, encoding = collate._locale.getpair(locale, encoding)
25 icu_locale = "root" if locale == "C" else locale
26 self._collator = _icu.Collator(icu_locale)
27 self.locale = self._collator.locale
28 self.encoding = collate._locale.encoding(encoding)
29 if self._collator.used_default_information and locale != "C":
30 raise collate.errors.InvalidLocaleError(locale)
31
32 try:
33 self._breaker = _icu.WordBreaker(icu_locale)
34 except ValueError:
35 # Thai is the only language with a special break locale,
36 # so this is a harmless error.
37 self._breaker = _icu.WordBreaker("root")
38
39 def key(self, string):
40 """Sort key for a string.
41
42 If the string is a str instance, it is decoded to a unicode
43 instance according to the 'encoding' attribute of the
44 Collator.
45 """
46 if isinstance(string, str):
47 string = string.decode(self.encoding, 'replace')
48 return self._collator.key(string)
49
50 def cmp(self, a, b):
51 """Return negative if a < b, zero if a == b, positive if a > b.
52
53 If strs rather than unicodes are passed in, they are first
54 decoded according to the 'encoding' attribute of the Collator.
55 """
56 if isinstance(a, str):
57 a = a.decode(self.encoding, 'replace')
58 if isinstance(b, str):
59 b = b.decode(self.encoding, 'replace')
60 return self._collator.cmp(a, b)