No Description
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

mlstring.py 2.5KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. # -*- coding: utf-8 -*-
  2. import json
  3. ## Handle string with translations
  4. # @todo define a default language that will be used in case the wanted language is not available for this string (gettext-like behavior)
  5. class MlString(object):
  6. ## Instanciate a new string with translation
  7. #
  8. # @param translations dict: With key = lang and value the translation
  9. def __init__(self, translations=None):
  10. self.translations = dict() if translations is None else translations
  11. ## Return a translation
  12. # @param lang str: The lang
  13. # @return An empty string if the wanted lang don't exist
  14. # @warning Returns an empty string if the wanted translation didn't exists
  15. # @todo if the asked language is not available, use the default one, defined as a class property
  16. def get(self, lang):
  17. if not lang in self.translations:
  18. return ''
  19. return self.translations[lang]
  20. ## Set a translation for this MlString
  21. # @param lang str: The language
  22. # @param text str: The translation
  23. # @todo check if the default language as a translation
  24. def set(self, lang, text):
  25. if not text:
  26. if lang in self.translations:
  27. del(self.translations[lang])
  28. else:
  29. self.translations[lang] = text
  30. def __repr__(self):
  31. return self.__str__()
  32. ## String representation
  33. # @return A json dump of the MlString::translations dict
  34. def __str__(self):
  35. if self.translations:
  36. return json.dumps(self.translations, sort_keys=True)
  37. else:
  38. return ""
  39. ## Test if two MlString instance are equivalent
  40. # @param other MlString|str : Another MlString instance or a string (json formated)
  41. # @return True or False
  42. def __eq__(self, other):
  43. if isinstance(other, str):
  44. other = MlString.load(other)
  45. if not isinstance(other, MlString):
  46. return False
  47. if not set(lng for lng in self.translations) == set( lng for lng in other.translations):
  48. return False
  49. for lng in self.translations:
  50. if self.get(lng) != other.get(lng):
  51. return False
  52. return True
  53. @staticmethod
  54. ## Instanciate a MlString from json
  55. # @param json_string str: Json datas in a string
  56. # @return A new MlString instance
  57. # @warning fails silently
  58. def load(json_string):
  59. if isinstance(json_string, str) and json_string != '':
  60. translations = json.loads(json_string)
  61. else:
  62. translations = dict()
  63. return MlString(translations)