[PyKDE] UI on the fly - in Python

Bruno da Silva de Oliveira bruno at esss.com.br
Thu Feb 10 20:57:33 GMT 2005


Torsten Marek wrote:

> I'm no expert on this, but if we get a parse tree of a Python file (is 
> this
> possible from within Python?), we could just walk the tree and put the 
> argument
> to every __tr (or whatever else) call into the message file.


Hi,

Answering your question, it is possible to get the parse tree of a 
Python file (look up the ast module). But while we are at it, I would 
like to request that we allow pylupdate to recognize other tokens beside 
self.__tr, possibly from a command line switch.

Here at work we modified the pylupdate source code to recognize "_" 
besides self.__tr, and use as context the name of the surce file 
(without the ".py" extension). The function "_" automagically recognizes 
the filename of the caller module, and uses this as the context for the 
qApp.translate call, and we put it in the builtin namespace for 
convenience. Here is the code for those interested:

# --- code ---
def tr(text):
    '''"Magic" translate function, that automatically uses as context 
the calling
    file.
   
    @note: this function assumes that we have patched pylupdate.exe from the
    PyQt distribution. Otherwise, the string literals won't be taken for
    translation.
    '''
    # get the calling filename
    try:
        f = sys._getframe(1)   
        filename = f.f_code.co_filename
    finally:
        del f

    # extract directory and extension
    context = os.path.basename(os.path.splitext(filename)[0])
    return translate(context, text)


# Installs the tr function as "_" in the builtin namespace.
import __builtin__
__builtin__._ = tr

# --- end of code ---

The usage is much nicer:

mymodule.py:

   _("Hello")

Instead of:

   self.__tr("Hello")

Plus the context of the first call is automatically assumed to be 
"mymodule" by pylupdate.

We find this solution much better, because forcing the programmer to 
define the context in the source file, in the form of a "def __tr" 
method, was too error prone; it was easy to mispell the context in the 
source file, or use the wrong one since pylupdate originally used the 
name found in the previous class statement. Consider:

class A:
   
    class B: pass

    def foo(self):
        self.__tr("hello")

    def __tr(self, text):
        return qApp.translate("A", text)

Here, the context generated by pylupdate is "B", which is clearly wrong. 
And since a missing translation simply returns the original string 
unchanged (there's no translation for "hello" in the context of "A"), it 
can take a while to figure what's happening.

Finally, the gettext standard also uses _() as the translation function 
(actually, a macro em C), so its not totally bizarre.

Any thoughts?

-- 
Bruno da Silva de Oliveira
bruno at esss.com.br
ESSS - Engineering Simulation and Scientific Software
http://www.esss.com.br




More information about the PyQt mailing list