Confused about `is` operator with strings

前端 未结 4 702
暗喜
暗喜 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:30

    Note that this is a CPython specific optimization. If you want your code to be portable, you should avoid it. For example, in PyPy

    >>>> a = "hi"
    >>>> b = "hi"
    >>>> a is b
    False
    

    It's also worth pointing out that a similar thing happens for small integers

    >>> a = 12
    >>> b = 12
    >>> a is b
    True
    

    which again you should not rely on, because other implementations might not include this optimization.

提交回复
热议问题