Opened 8 years ago

Last modified 7 years ago

#18995 new Cleanup/optimization

String formatting error when passing floats as values in {% blocktrans %} tags

Reported by: Bruno Renié Owned by: nobody
Component: Internationalization Version: 1.4
Severity: Normal Keywords:
Cc: Triage Stage: Accepted
Has patch: no Needs documentation: no
Needs tests: no Patch needs improvement: no
Easy pickings: no UI/UX: no


With the following template code:

{% blocktrans count counter=person.distance_in_miles|floatformat:0 %}{{ counter }} mile away{% plural %}{{ counter }} miles away{% endblocktrans %}

And a russian translation:

#, python-format
msgid "%(counter)s mile away"
msgid_plural "%(counter)s miles away"
msgstr[0] "На расстоянии %(counter)s мили"
msgstr[1] "На расстоянии %(counter)s миль"
msgstr[2] "На расстоянии %(counter)s миль"

Rendering the template fails with a String formatting error: "TypeError: not all arguments converted during string formatting".

This happens because gettext string formatting fails when a float is passed. Removing the floatformat and casting the value as int works fine.

This could be improved by either:

  • Swallow TypeError and throw a friendlier message saying the type might not be compatible with gettext's string formatting (not a fan of swallowing TypeError though, we need to make sure nothing else in do_translate throws such an exception)
  • Actively checking the type's compatibility with the string format

Change History (2)

comment:1 Changed 8 years ago by Claude Paroz

Triage Stage: UnreviewedAccepted
Type: UncategorizedCleanup/optimization

comment:2 Changed 7 years ago by Julien Phalip

I've done some digging and found that the issue isn't to do with floats. In fact, ungettext will happily work with floats without raising any exceptions.

The root of the problem is that floatformat returns a string, which conflicts with the Russian plural rules. Indeed, those rules use the modulo sign %:

"Plural-Forms: nplurals=3; plural=(n%10==1 && n%100!=11 ? 0 : n%10>=2 && n"
"%10<=4 && (n%100<10 || n%100>=20) ? 1 : 2);\n"

If you pass a string as a value for n, then the % sign will operate as string formatting instead of a modulo, therefore causing the TypeError. The same effect can be easily reproduced as follows:

>>> '123' % 10
*** TypeError: not all arguments converted during string formatting

I suggest making blocktrans raise an exception upstream if the value provided for the counter is not a number.

Note: See TracTickets for help on using tickets.
Back to Top