utils.functional.keep_lazy()

keep_lazy(func, *resultclasses) [source]

New in Django 1.10.

Django offers many utility functions (particularly in django.utils) that take a string as their first argument and do something to that string. These functions are used by template filters as well as directly in other code.

If you write your own similar functions and deal with translations, you’ll face the problem of what to do when the first argument is a lazy translation object. You don’t want to convert it to a string immediately, because you might be using this function outside of a view (and hence the current thread’s locale setting will not be correct).

For cases like this, use the django.utils.functional.keep_lazy() decorator. It modifies the function so that if it’s called with a lazy translation as one of its arguments, the function evaluation is delayed until it needs to be converted to a string.

For example:

from django.utils import six
from django.utils.functional import keep_lazy, keep_lazy_text

def fancy_utility_function(s, ...):
    # Do some conversion on string 's'
    ...
fancy_utility_function = keep_lazy(six.text_type)(fancy_utility_function)

# Or more succinctly:
@keep_lazy(six.text_type)
def fancy_utility_function(s, ...):
    ...

The keep_lazy() decorator takes a number of extra arguments (*args) specifying the type(s) that the original function can return. A common use case is to have functions that return text. For these, you can just pass the six.text_type type to keep_lazy (or even simpler, use the keep_lazy_text() decorator described in the next section).

Using this decorator means you can write your function and assume that the input is a proper string, then add support for lazy translation objects at the end.

doc_Django
2016-10-09 18:40:29
Comments
Leave a Comment

Please login to continue.