|
| 1 | +from typing import Iterable, Optional, Set |
1 | 2 | from banal import ensure_list |
2 | 3 |
|
3 | 4 | from languagecodes.iso639 import ISO3_ALL, ISO2_MAP, ISO3_MAP |
4 | 5 | from languagecodes.synonyms import expand_synonyms |
5 | 6 | from languagecodes.util import normalize_code |
6 | 7 |
|
7 | 8 |
|
8 | | -def iso_639_alpha3(code): |
| 9 | +def iso_639_alpha3(code: str) -> Optional[str]: |
9 | 10 | """Convert a given language identifier into an ISO 639 Part 2 code, such |
10 | 11 | as "eng" or "deu". This will accept language codes in the two- or three- |
11 | 12 | letter format, and some language names. If the given string cannot be |
12 | 13 | converted, ``None`` will be returned. |
13 | 14 | """ |
14 | | - code = normalize_code(code) |
15 | | - code = ISO3_MAP.get(code, code) |
16 | | - if code in ISO3_ALL: |
17 | | - return code |
| 15 | + norm = normalize_code(code) |
| 16 | + if norm is not None: |
| 17 | + norm = ISO3_MAP.get(norm, norm) |
| 18 | + if norm not in ISO3_ALL: |
| 19 | + return None |
| 20 | + return norm |
18 | 21 |
|
19 | 22 |
|
20 | | -def iso_639_alpha2(code): |
| 23 | +def iso_639_alpha2(code: str) -> Optional[str]: |
21 | 24 | """Convert a language identifier to an ISO 639 Part 1 code, such as "en" |
22 | 25 | or "de". For languages which do not have a two-letter identifier, or |
23 | 26 | invalid language codes, ``None`` will be returned. |
24 | 27 | """ |
25 | | - code = iso_639_alpha3(code) |
26 | | - return ISO2_MAP.get(code) |
| 28 | + alpha3 = iso_639_alpha3(code) |
| 29 | + if alpha3 is None: |
| 30 | + return None |
| 31 | + return ISO2_MAP.get(alpha3) |
27 | 32 |
|
28 | 33 |
|
29 | | -def list_to_alpha3(languages, synonyms=True): |
| 34 | +def list_to_alpha3(languages: Iterable[str], synonyms: bool = True) -> Set[str]: |
30 | 35 | """Parse all the language codes in a given list into ISO 639 Part 2 codes |
31 | 36 | and optionally expand them with synonyms (i.e. other names for the same |
32 | 37 | language).""" |
|
0 commit comments