rasky at develer.com
Wed Feb 11 17:36:23 GMT 2009
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
>>> frame = sys._getframe(1)
>>> fileName = frame.f_code.co_filename
>>> del frame
>>> context = os.path.basename(os.path.splitext(fileName))
>>> return unicode(QtCore.QCoreApplication.translate(context, text,
>>> def markNoTranslate(text, comment=''):
>>> """Mark text for translation without actually doing the
>>> return text
>>> __builtin__._ = translate
>>> __builtin__.N_ = markNoTranslate
>> 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
> 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:
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.
This said, I don't agree with the recommendation of not using self.tr().
In my experience, there are only a few cases where this turns out to be
a problem, compared to the benefits of code readability of self.tr().
For those cases in which it is a problem, the alternative is to use
qApp.translate(), which is a much shorter synonymous of
QtCore.QCoreApplication.translate :) (OK I'm cheating: I'm not taking
into account that I can use 'qApp' because of star-imports).
More information about the PyQt