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.1KB

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