Nessuna descrizione
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.4KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  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=dict()):
  10. self.translations = 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. ## String representation
  31. # @return A json dump of the MlString::translations dict
  32. def __str__(self):
  33. if self.translations:
  34. return json.dumps(self.translations)
  35. else:
  36. return ""
  37. ## Test if two MlString instance are equivalent
  38. # @param other MlString|str : Another MlString instance or a string (json formated)
  39. # @return True or False
  40. def __eq__(self, other):
  41. if isinstance(other, str):
  42. other = MlString.load(other)
  43. if not isinstance(other, MlString):
  44. return False
  45. if not set(lng for lng in self.translations) == set( lng for lng in other.translations):
  46. return False
  47. for lng in self.translations:
  48. if self.get(lng) != other.get(lng):
  49. return False
  50. return True
  51. @staticmethod
  52. ## Instanciate a MlString from json
  53. # @param json_string str: Json datas in a string
  54. # @return A new MlString instance
  55. # @warning fails silently
  56. def load(json_string):
  57. if isinstance(json_string, str) and json_string != '':
  58. translations = json.loads(json_string)
  59. else:
  60. translations = dict()
  61. return MlString(translations)