tags:

views:

50

answers:

3

Hi there,

I would like to use gettext through my application.

So, I tried to put the basics into __ init__.py like this :

import gettext
_ = gettext.gettext

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

And I try 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 I have the following error at execution time :

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

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

Could you give me good advices ?

Thanks,

Damien

+2  A: 

Wildcard imports don't import anything beginning with an underscore.

Wildcards are bad, they pollute the namespace, and create hard to find bugs. Also, the _ is sometimes used to denote an unused variable.

Just do the import where you need it. It's only one line, so it's not hard to type in, and you could always create a snippet in your IDE.

UPDATE: See http://python.net/~goodger/projects/pycon/2007/idiomatic/handout.html#importing for even more reasons not to use wildcards.

sdolan
Thank you very much, as you said, it is not so hard to add just a line at the beginning of the file. So I will use " from gettext import gettext as _ ".
MARTIN Damien
+1  A: 

sdolan's answer is correct and adding the link for your information on this:

pyfunc
1st link doesn't have anything to do with this. 2nd is good though So that gets you a +1/2, which I'll round up :)
sdolan
@sdolan : I thought, since I have provided the link for "_", I as well lead up to the "__" so that all that is read in one go! Thanks :)
pyfunc
A: 

This is pure evil, but it does what you want. In the _init.py_ root of your project, do this:

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

And now the underscore will be ugettext everywhere. The other answers have appropriate caveats; modifying the python VM's builtins list isn't very nice, and it surely will confuse the hell out of anyone who's not familiar with it.

Elf Sternberg