Confused about `is` operator with strings

前端 未结 4 710
暗喜
暗喜 2020-12-11 17:56

The is operator compares the memory addresses of two objects, and returns True if they\'re the same. Why, then, does it not work reliably with stri

4条回答
  •  余生分开走
    2020-12-11 18:11

    is is identity testing. It will work on smaller some strings(because of cache) but not on bigger other strings. Since str is NOT a ptr. [thanks erykson]

    See this code:

    >>> import dis
    >>> def fun():
    ...   str = 'today is a fine day'
    ...   ptr = 'today is a fine day'
    ...   return (str is ptr)
    ...
    >>> dis.dis(fun)
      2           0 LOAD_CONST               1 ('today is a fine day')
                  3 STORE_FAST               0 (str)
    
      3           6 LOAD_CONST               1 ('today is a fine day')
                  9 STORE_FAST               1 (ptr)
    
      4          12 LOAD_FAST                0 (str)
                 15 LOAD_FAST                1 (ptr)
                 18 COMPARE_OP               8 (is)
                 21 RETURN_VALUE
    
    >>> id(str)
    26652288
    >>> id(ptr)
    27604736
    #hence this comparison returns false: ptr is str
    

    Notice the IDs of str and ptr are different.

    BUT:

    >>> x = "poi"
    >>> y = "poi"
    >>> id(x)
    26650592
    >>> id(y)
    26650592
    #hence this comparison returns true : x is y
    

    IDs of x and y are the same. Hence is operator works on "ids" and not on "equalities"

    See the below link for a discussion on when and why python will allocate a different memory location for identical strings(read the question as well).

    When does python allocate new memory for identical strings

    Also sys.intern on python3.x and intern on python2.x should help you allocate the strings in the same memory location, regardless of the size of the string.

提交回复
热议问题