4

I am studying web2py. I read example open source code. In one application (storpy), the programmer uses T.lazy repeatedly inside the models file db.py such as this:

...
Field('comment', 'text'),
Field('cover', 'upload', autodelete=True))

T.lazy = False
db.dvds.title.requires = [IS_NOT_EMPTY(error_message=T('Missing data') + '!'), IS_NOT_IN_DB(db, 'dvds.title', error_message=T('Already in the database') + '!')]
...
T.lazy = True

Why does the programmer set T.lazy first to False then to True?

Mert Nuhoglu
  • 9,695
  • 16
  • 79
  • 117

1 Answers1

5

By default, T() is lazy -- when you call it, it doesn't actually do the translation but instead returns a lazyT object, which isn't translated until serialized in a view. If you set T.lazy=False, that will force immediate translation, so calling T('some string') will return the actual translated string instead of a lazyT object.

Note, starting with the upcoming release, instead of having to toggle T.lazy to False and True, you will be able to do T('some string', lazy=False) to force an immediate translation for a single call. Other ways to force immediate translation are str(T('some string')) or T('some string').xml() -- str() serializes the lazyT object (and .xml() simply calls str()).

Anthony
  • 25,466
  • 3
  • 28
  • 57
  • Thank you for the clear explanation. One more question: Why is there a need for immediate translation? – Mert Nuhoglu Nov 10 '11 at 18:07
  • 3
    For example, sometimes date formats like '%Y/%m/%d' are translated but need to be passed to functions internally, such as `date.strftime(T('%Y/%m/%d', lazy=False))`. – Anthony Nov 10 '11 at 19:45