Python: using gettext everywhere with __init__.py

I would like to use gettext through my application.

So, I tried putting the basics in __ init__.py like this:

import gettext
_ = gettext.gettext

gettext.bindtextdomain ( 'brainz', '../datas/translations/' )
gettext.textdomain ( 'brainz' )

And try a simple call in Brainz.py:

#!/usr/bin/python

from brainz import *

##
# Main class of the game
class Brainz :

    def __init__ ( self ) :

        print _( "BrainZ" )
        print _( "There will be blood..." )
        print _( "By %s" ) % "MARTIN Damien"

But at runtime, I have the following error:

Traceback (most recent call last):
  File "main.py", line 8, in <module>
    Brainz ()
  File "/home/damien/Dropbox/Projets/BrainZ/brainz/Brainz.py", line 12, in __init__
    print _( "BrainZ" )
NameError: global name '_' is not defined

Since I'm new to python, I don't understand what is wrong.

Could you give me some good advice?

Thank,

Damien

+5
source share
3 answers

sdolan explained why your code is not working and provided a great solution. But it has some inconvenience: you need to import gettext into each module that you want to include.

Elf Sternberg : gettext . , , , :). , , Django ugettext. Django, lib gettext, .

, ? __init__.py, , :

import gettext
gettext.install('brainz', '../datas/translations/')

! _() , gettext. , , gettext, , , . , , Pure Evil (tm). , "brainz" .

"brainz" , sdolan: . , , bindtextdomain textdomain, , :

import gettext
t = gettext.translation('brainz', '../datas/translations/')
_ = t.ugettext

API- gettext API- GNU gettext. . install API .

: , pygettext GNU xgettext. ! Pygettext . xgettext Python.

+5

, , . _init.py_ :

from django.utils.translation import ugettext
import __builtin__
__builtin__.__dict__['_'] = ugettext

. ; python , , .

+1

All Articles