Simulate a dict for DjangoTranslation._catalog so as multiple catalogs with different plural equations are kept separate.
| 71 | |
| 72 | |
| 73 | class TranslationCatalog: |
| 74 | """ |
| 75 | Simulate a dict for DjangoTranslation._catalog so as multiple catalogs |
| 76 | with different plural equations are kept separate. |
| 77 | """ |
| 78 | |
| 79 | def __init__(self, trans=None): |
| 80 | self._catalogs = [trans._catalog.copy()] if trans else [{}] |
| 81 | self._plurals = [trans.plural] if trans else [lambda n: int(n != 1)] |
| 82 | |
| 83 | def __getitem__(self, key): |
| 84 | for cat in self._catalogs: |
| 85 | try: |
| 86 | return cat[key] |
| 87 | except KeyError: |
| 88 | pass |
| 89 | raise KeyError(key) |
| 90 | |
| 91 | def __setitem__(self, key, value): |
| 92 | self._catalogs[0][key] = value |
| 93 | |
| 94 | def __contains__(self, key): |
| 95 | return any(key in cat for cat in self._catalogs) |
| 96 | |
| 97 | def items(self): |
| 98 | for cat in self._catalogs: |
| 99 | yield from cat.items() |
| 100 | |
| 101 | def keys(self): |
| 102 | for cat in self._catalogs: |
| 103 | yield from cat.keys() |
| 104 | |
| 105 | def update(self, trans): |
| 106 | # Merge if plural function is the same as the top catalog, else |
| 107 | # prepend. |
| 108 | if trans.plural.__code__ == self._plurals[0]: |
| 109 | self._catalogs[0].update(trans._catalog) |
| 110 | else: |
| 111 | self._catalogs.insert(0, trans._catalog.copy()) |
| 112 | self._plurals.insert(0, trans.plural) |
| 113 | |
| 114 | def get(self, key, default=None): |
| 115 | missing = object() |
| 116 | for cat in self._catalogs: |
| 117 | result = cat.get(key, missing) |
| 118 | if result is not missing: |
| 119 | return result |
| 120 | return default |
| 121 | |
| 122 | def plural(self, msgid, num): |
| 123 | for cat, plural in zip(self._catalogs, self._plurals): |
| 124 | tmsg = cat.get((msgid, plural(num))) |
| 125 | if tmsg is not None: |
| 126 | return tmsg |
| 127 | raise KeyError |
| 128 | |
| 129 | |
| 130 | class DjangoTranslation(gettext_module.GNUTranslations): |