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.
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.
- [Django]-Dynamic SEO-friendly URLs
- [Django]-Django: filter JSONField with multiple nested arrays
- [Django]-How to correctly load data from a table to a form?
- [Django]-Saving a Pillow file to S3 with boto