Hi Steve,
On 04/07/2016 05:09 PM, Stephen Kelly wrote:
> Am I right to think that using 'is' with numbers is expected to work like
> this in the DTL? :
The situation with integers is roughly the same as with strings, except
that I believe CPython interns _all_ small integers, not just those that
are literals in the code. This happens to make DTL appear a bit more
"consistent" with CPython for integers, but the correct advice is still
the same: don't ever use `is` with integers, whether in Python code or DTL.
The `is` operator tells you whether two variables refer to the same
object. This is sometimes a meaningful question to ask for instances of
classes with mutable state, or for singletons like None, True, and
False, but it's not a useful or meaningful question to ask about
immutable objects like strings and integers, because there is no
perceptible difference (other than from `is`, `id`, and perhaps memory
usage) resulting from whether the implementation happened to choose to
reuse the same object or not.
> In [120]: c["a"] = 1
>
> In [121]: t = e.from_string("{% if 1 is 1 %}yes{% else %}no{% endif %}")
>
> In [122]: print t.render(c)
> yes
>
> In [123]: t = e.from_string("{% if 1 is a %}yes{% else %}no{% endif %}")
>
> In [124]: print t.render(c)
> yes
>
> In [125]: c["a"] = 1.0
>
> In [126]: t = e.from_string("{% if 1 is a %}yes{% else %}no{% endif %}")
>
> In [127]: print t.render(c)
> no
>
> In [128]: t = e.from_string("{% if 1 is 1.0 %}yes{% else %}no{% endif
> %}")
>
> In [129]: print t.render(c)
> no
>
> In [130]: t = e.from_string("{% if 1.0 is 1.0 %}yes{% else %}no{% endif
> %}")
>
> In [131]: print t.render(c)
> no
>
> Would it be useful to add those as unit tests and document what can be
> expected of 'if ... is'?
No to tests, because we would be adding tests for undefined and
unreliable behavior.
It might be worth adding a short documentation note. We largely want to
avoid documenting Python's behavior in the Django docs, but a short note
in the template `is` docs reminding people not to ever use `is` with
strings or numbers might be worthwhile.
Carl