[Django]-A weird string literal identity issue in Django

4πŸ‘

βœ…

Do not rely on string comparison by identity, in any cases. The fact that it appears to work sometimes is due to an implementation detail of CPython called string interning. The rules governing whether a given string will be interned or not are very complicated, and subject to change without notice.

For example, with a slight modification of your original example we can change the behaviour:

>>> x = {'command': 'activate.'}
>>> x['command'] is 'activate.'
False

Use == and != for string comparisons.

πŸ‘€wim

0πŸ‘

But, again, as far as I know, literals should have the same identity no matter where they come from.

First, that’s not actually true. Unlike, say, Java, Python makes no guarantees about whether literals are interned:

In [1]: x = 'a b'

In [2]: x is 'a b'
Out[2]: False

Second, the 'activate' in request.data['command'] is coming from a parsed network request, not a string literal.

πŸ‘€user2357112

Leave a comment