[PyQt] i18n
Doug Bell
dougb at bellz.org
Wed Feb 11 18:22:38 GMT 2009
Giovanni Bajo wrote:
> On 2/11/2009 5:58 PM, Doug Bell wrote:
>> Frédéric wrote:
>>> On mercredi 11 février 2009, Doug Bell wrote:
>>>
>>>>> Are there some tips, for example, to bind the _() method I use with
>>>>> gettext and PyGTK? Something to help me migrate my code without having
>>>>> to modify it everywhere...
>>>> Here's how I do it:
>>>>
>>>> def translate(text, comment=''):
>>>> """Translation function that sets context to calling module's
>>>> filename"""
>>>> try:
>>>> frame = sys._getframe(1)
>>>> fileName = frame.f_code.co_filename
>>>> finally:
>>>> del frame
>>>> context = os.path.basename(os.path.splitext(fileName)[0])
>>>> return unicode(QtCore.QCoreApplication.translate(context, text,
>>>> comment))
>>>>
>>>> def markNoTranslate(text, comment=''):
>>>> """Mark text for translation without actually doing the
>>>> translation"""
>>>> return text
>>>>
>>>> __builtin__._ = translate
>>>> __builtin__.N_ = markNoTranslate
>>> Thanks!
>>>
>>> What is the purpose of the N_() function?
>>
>> It's for cases where you want to mark a string to be included in the
>> language files, but you don't want to change the string by doing the
>> translation immediately. An example would be a string used as a key in
>> an untranslated data file that later needs to be translated for output.
>> The N_() function applied to the string literal would just mark it, then
>> the _() function could be applied later to a variable containing that
>> string.
>>
>> Note that you will also need to slightly modify the pylupdate program
>> to look for the _() and N_() functions and to use the proper context.
>
> It looks like a little too much effort. For such cases, what we usually
> do is something like:
>
> if 0:
> self.tr("text 1")
> self.tr("text 2")
> self.tr("text 3")
> self.tr("text 4")
> self.tr("text 5")
The case I was trying to explain is when you want to assign the string
to a variable, use the variable untranslated (such as for a dictionary
or data file key), and then output a translated version of the variable.
The "if 0:" approach doesn't work if you want to assign the string to a
variable without repeating the string literal.
> and you're done. Moreover: if those strings comes from a data file,
> you can even write a generator that parses the data file, produces a
> file like the above snippet, and feed it to pylupdate. You don't need
> a custom pylupdate for sure.
I think I need to clarify my response. The primary reason for the
custom pylupdate is not to make the delayed translation function work.
It is needed to make modules written with gettext translation functions
(_() and N_()) work with the Qt translation engine. That was one of the
original poster's requests. It also came in handy on one of my
projects, where I wanted my non-gui modules to also work with Python
gettext for a console version of the app.
Doug.
More information about the PyQt
mailing list