“is” operator not working as intended

后端 未结 3 1163
小鲜肉
小鲜肉 2021-01-15 12:02

Just have a look at this code:

import re

ti = \"abcd\"
tq = \"abcdef\"
check_abcd = re.compile(\'^abcd\')
print id(check_abcd.search(ti))
print id(check_abc         


        
3条回答
  •  日久生厌
    2021-01-15 12:49

    You never assigned the return values, so after printing the id() value of the return value of check_abcd.search() calls, Python discards the return value object as there is nothing referencing it anymore. CPython object lifetimes are directly governed by the number of references to them; as soon as that reference count drops to 0 the object is removed from memory.

    Discarded memory locations can be re-used, so you'll like to see the same values crop up in id() calls. See the id() documentation:

    Return the “identity” of an object. This is an integer (or long integer) which is guaranteed to be unique and constant for this object during its lifetime. Two objects with non-overlapping lifetimes may have the same id() value.

    At no point in your code did you actually have one object, you have two separate objects with non-overlapping lifetimes.

    Assign return values if you want to make sure id() values are not reused:

    >>> import re
    >>> ti = "abcd"
    >>> tq = "abcdef"
    >>> check_abcd = re.compile('^abcd')
    >>> ti_search = check_abcd.search(ti)
    >>> tq_search = check_abcd.search(tq)
    >>> id(ti_search), id(tq_search)
    (4378421952, 4378422056)
    >>> ti_search, tq_search
    (<_sre.SRE_Match object at 0x104f96ac0>, <_sre.SRE_Match object at 0x104f96b28>)
    >>> ti_search is tq_search
    False
    

    By assigning the return values of check_abcd.search() (the regular expression MatchObjects) an additional reference is created and Python cannot reuse the memory location.

提交回复
热议问题