Coverage for portality / lib / isolang.py: 100%

16 statements  

« prev     ^ index     » next       coverage.py v7.13.5, created at 2026-05-04 09:41 +0100

1import pycountry 

2 

3 

4def find(lang: str): 

5 """ Look up a language preferably by alpha2 code, or any of its attributes 

6 

7 :param lang: A code or name, etc. to retrieve the language record 

8 :return: a dictionary equivalent to the pycountry representation of a record 

9 """ 

10 return _as_dict(find_raw(lang)) 

11 

12 

13def find_raw(lang: str): 

14 """ 

15 Look up a language preferably by alpha2 code, or any of its attributes 

16 

17 :param lang: A code or name, etc. to retrieve the language record 

18 :return: the pycountry representation of a language 

19 """ 

20 

21 language = pycountry.languages.get(alpha_2=lang) 

22 if language is None: 

23 try: 

24 return pycountry.languages.lookup(lang) 

25 except LookupError: 

26 return None 

27 return language 

28 

29 

30def _as_dict(language_object: pycountry.Languages): 

31 """ Get a dict representing a language """ 

32 # Previously we had a list of ISO_639_2b (bibliographic) languages in datasets.py represented e.g. 

33 # [u"wel", u"cym", u"cy", u"Welsh", u"gallois"] - now we have pycountry, so we favour the bibliographic name when 

34 # available. French is no longer present. 

35 

36 if language_object is None: 

37 return None 

38 

39 # Convert to a dict in pycountry's representation 

40 language_dict = vars(language_object)['_fields'] 

41 

42 return { 

43 "alpha3": language_dict.get('bibliographic', language_dict.get('alpha_3', '')), 

44 "alt3": language_dict.get('alpha_3', ''), 

45 "alpha2": language_dict.get('alpha_2', ''), 

46 "name": language_dict.get('name', ''), 

47 "fr": '' 

48 }