Carl Meyer wrote:

> The point is that you shouldn't ever expect any consistent behavior when
> using `is` with strings (whether in Python code or in Django templates),
> because that behavior is not defined by the Python language, it's
> implementation dependent. It happens that the CPython implementation
> interns short string literals, so they are the same object in memory,
> but this doesn't happen for longer strings, or strings that aren't
> generated from literals. Those "string literals" in the Django template
> are not string literals from Python's perspective, so they are not
> interned, so they are not the same object.
> 
> There's no reasonable way to "fix" this, because there is no reliable
> Python behavior to try to match. Any fix would just be encouraging use
> of `is` with strings; the right answer is "never use `is` with strings"
> (or with integers, for exactly the same reasons).
> 
> In other words, the value of `"string" is "string"` in Python is
> effectively accidental and almost certainly useless (it does correctly
> and reliably tell you whether the two string objects are the same
> object, but for immutable objects this information is
> performance-optimization-dependent and useless), so there is no
> "correct" behavior here for the DTL to match.

I see, and I understand now. Thanks for the explanation and sorry for being 
slow on the uptake on this one!

Am I right to think that using 'is' with numbers is expected to work like 
this in the DTL? :

    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'?

Thanks,

Steve.


-- 
You received this message because you are subscribed to the Google Groups 
"Django developers  (Contributions to Django itself)" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-developers+unsubscr...@googlegroups.com.
To post to this group, send email to django-developers@googlegroups.com.
Visit this group at https://groups.google.com/group/django-developers.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-developers/ne6pap%24n52%241%40ger.gmane.org.
For more options, visit https://groups.google.com/d/optout.

Reply via email to