Skip to content
Myr

Fixed int() filter for non-string objects #466

Before adoption: this commit came in with the history the project adopted, so no landing records it.

authored by Sebastian Noack · committed by Markus Unterwaditzer · parent 8189d21 · Browse files · 2 files+12 added−4 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

2 files+12 added−4 removed

  • tests:+8 added−3 removed
  • other:+4 added−1 removed

2 files+12 added−4 removed

modified:jinja2/filters.py+4 added-1 removed
516 unmodified lines
517 override this default using the first parameter. You518 can also override the default base (10) in the second519 parameter, which handles input with prefixes such as520 0b, 0o and 0x for bases 2, 8 and 16 respectively.521 The base is ignored for decimal numbers and non-string values.522 """523 try:524 if isinstance(value, string_types):523 return int(value, base)525 return int(value, base)526 return int(value)527 except (TypeError, ValueError):528 # this quirk is necessary so that "42.23"|int gives 42.529 try:530 return int(float(value))
469 unmodified lines
modified:tests/test_filters.py+8 added-3 removed
131 unmodified lines
132 assert out == ('foo bar foo bar\n foo bar foo bar| '133 'foo bar foo bar\n foo bar foo bar')134135 def test_int(self, env):136 class IntIsh(object):137 def __int__(self):138 return 42139140 tmpl = env.from_string('{{ "42"|int }}|{{ "ajsghasjgd"|int }}|'141 '{{ "32.32"|int }}|{{ "0x4d32"|int(0, 16) }}|'138 '{{ "011"|int(0, 8)}}|{{ "0x33FU"|int(0, 16) }}')139 out = tmpl.render()140 assert out == '42|0|32|19762|9|0'142 '{{ "011"|int(0, 8)}}|{{ "0x33FU"|int(0, 16) }}|'143 '{{ obj|int }}')144 out = tmpl.render(obj=IntIsh())145 assert out == '42|0|32|19762|9|0|42'146147 def test_join(self, env):148 tmpl = env.from_string('{{ [1, 2, 3]|join("|") }}')149 out = tmpl.render()
414 unmodified lines