[openstack-dev] [oslo] i18n Message improvements
Luis A. Garcia
luis at linux.vnet.ibm.com
Fri Oct 18 17:55:45 UTC 2013
On 10/17/2013 10:13 AM, John S Warren wrote:
> [snip]
> Instead of faking unicode behavior, I'm suggesting that we use its
> functionality in Message as-is, only overriding the __mod__ method
> in order to support translation in downstream code. In short, the
> Message class would differ from unicode in only these ways:
>
> 1. A "translate" method is introduced.
> 2. Attributes necessary to perform the translation operation (e.g.
> message ID) are added.
> 3. The __mod__ method is overridden to preserve the parameters so
> they can be used in case a translation operation is needed.
>
> So I guess where we differ is in that I don't see the need to have
> Message objects that are distinct from unicode objects. It seems
> to me that having _() return objects that can be used in the same
> manner as the ones returned by the original gettext implementation
> avoids a lot of complications. Because Message is extending unicode,
> and it is not overriding any of the relevant behaviors, for all intents
> and purposes it's not pretending to be something it isn't when an
> instance of it is being used as a unicode object would be used.
+1
Yeah, I think this is the way to go, it would solve all the problems we
are seeing with "trying" to look and feel like unicode, when the Message
class is not, but it would also greatly remove a lot of teh "magic" and
complexity previously in the Message class.
Basically the Message class would look like this (I changed the name too):
class TranslatableUnicode(unicode):
def __new__(cls, *args, **kwargs):
return super(TranslatableUnicode, cls).__new__(cls, args[0])
def __init__(self, msgid, domain):
self.domain = domain
self.msgid = msgid
self.params = None
def __mod__(self, other):
# We just save the params in case they are needed in a translation
self.params = other
return super(TranslatableUnicode, self).__mod__(other)
def translate(self, locale):
localedir = os.environ.get(self.domain.upper() + '_LOCALEDIR')
if not locale:
locale = locale.getdefaultlocale()
lang = gettext.translation(self.domain,
localedir=localedir,
languages=[locale],
fallback=True)
ugettext = lang.gettext if six.PY3 else lang.ugettext
translated = ugettext(self.msgid)
if self.params is not None:
# Recurse and translate parameters
translated = translated % self.params
return translated
--
Luis A. García
Cloud Solutions & OpenStack Development
IBM Systems and Technology Group
Ph: (915) 307-6568 | T/L: 363-6276
"Everything should be made as simple as possible, but not simpler."
- Albert Einstein
"Simple can be harder than complex: You have to work hard to get
your thinking clean to make it simple."
– Steve Jobs
More information about the OpenStack-dev
mailing list