views:

204

answers:

3

When reading source code of Django, I find some statements:

class Field(object):  
    """Base class for all field types"""  
    __metaclass__ = LegacyConnection  

    # Generic field type description, usually overriden by subclasses
    def _description(self):
        return _(u'Field of type: %(field_type)s') % {
            'field_type': self.__class__.__name__
        }    
    description = property(_description) 

class AutoField(Field):
    description = _("Integer")

I know it set description as 'Integer', but don't understand the syntax: description = _("Integer").
Can some one help on it?

+10  A: 

Please read up on Internationalization (i18n)

http://docs.djangoproject.com/en/dev/topics/i18n/

The _ is a commonly-used name for the function that translates strings to another language.

http://docs.djangoproject.com/en/dev/topics/i18n/internationalization/#standard-translation

Also, read all of these related questions on SO:

http://stackoverflow.com/search?q=%5Bdjango%5D+i18n

S.Lott
got it, thanks for the detail message! :)
Beyonder
+5  A: 

this is used for gettext function, as is described here

Utf-8 support of django is good, so django handles it as unicodetext as described here

FallenAngel
got it, thanks for the detail message! :)
Beyonder
+2  A: 

Not an answer to your case but the more general "What's the meaning of '_' in python?":

In interactive mode, a _ will return the last result that wasn't assigned to a variable

>>> 1 # _ = 1
1
>>> _ # _ = _
1
>>> a = 2
>>> _
1
>>> a # _ = a
2
>>> _ # _ = _
2
>>> list((3,)) # _ = list((3,))
[3]
>>> _ # _ = _
[3]

Not sure, but it seems like every expression that's not assigned to a variable is actually assigned to _.

Nick T
It seems there is another usage of '_' in python program. Such as:I_need, _, I_need_2 = ('a', 'b', 'c');in this case, you don't care about the second value in the tuple, so it saves your time to think up some variable names for these useless values which makes the code easier to read.
Beyonder
@Beyonder: True, but in that instance it's acting like any other variable, just using the most forgettable name possible `_` to say "I'm a throwaway variable".
Nick T