Code

Opened 22 months ago

Last modified 12 months ago

#18995 new Cleanup/optimization

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

Reported by: brutasse 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

Description

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

Attachments (0)

Change History (2)

comment:1 Changed 21 months ago by claudep

  • Needs documentation unset
  • Needs tests unset
  • Patch needs improvement unset
  • Triage Stage changed from Unreviewed to Accepted
  • Type changed from Uncategorized to Cleanup/optimization

comment:2 Changed 12 months ago by julien

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.

Add Comment

Modify Ticket

Change Properties
<Author field>
Action
as new
The owner will be changed from nobody to anonymous. Next status will be 'assigned'
as The resolution will be set. Next status will be 'closed'
Author


E-mail address and user name can be saved in the Preferences.

 
Note: See TracTickets for help on using tickets.