Can (s is ") and (s ==" ") ever give different results in Python 2.6.2?

As any Python programmer knows, you should use ==instead isto compare two lines for equality. However, are there really cases when ( s is "" )they ( s == "" )will give different results in Python 2.6.2?

I recently met code that I used ( s is "" )in a code review, and, pointing out that it was wrong, I wanted to give an example of how this could happen. But be that as it may, I cannot build two empty lines with different identifiers. It seems like the Python implementation should have a special case of empty string in a lot of common operations. For instance:

>>> a = ""
>>> b = "abc"[ 2:2 ]
>>> c = ''.join( [] )
>>> d = re.match( '()', 'abc' ).group( 1 )
>>> e = a + b + c + d 
>>> a is b is c is d is e
True

However, this question suggests that there are times when ( s is "" )they ( s == "" )can be different. Can someone give me an example?

+5
source share
7 answers

Like everyone else, do not rely on undefined behavior. However, since you requested a specific counterexample for Python 2.6, here it is:

>>> s = u"\xff".encode('ascii', 'ignore')
>>> s
''
>>> id(s)
10667744
>>> id("")
10666064
>>> s == ""
True
>>> s is ""
False
>>> type(s) is type("")
True

, Python 2.6 , , - , , . , , . , Python 2.7.

+11

Python is , . is == :

>>> s=u""
>>> print s is ""
False
>>> print s==""
True
+12

. None, , , , . , s is "" , is NO-NO, .

+7

, , , -, (, str - ), .

>>> class mysub(str):
    def __init__(self, *args, **kwargs):
        super(mysub, self).__init__(*args, **kwargs)

>>> 
>>> q = mysub("")
>>> q is ""
False
>>> q == ""
True

:

, , ( , ).

if x is ""

, x , , api ..

if x == ""

, x

+3

, - Python , is. (), '',u'', True, False, None CPython , .. 0, 0.0, 1, 1.0,

+1

, , CPython, -, "" . , , .

0

Undefined . , Python , , , . , Python, ( unicode vs. non-unicode , ). , .

Python , . , .

, : . . , .

0
source

All Articles