How do I check if two variables reference the same object in Python?

梦想的初衷 提交于 2019-12-03 19:09:24

问题


x and y are two variables.
I can check if they're equal using x == y, but how can I check if they have the same identity?

Example:

x = [1, 2, 3]
y = [1, 2, 3]

Now x == y is True because x and y are equal, however, x and y aren't the same object.
I'm looking for something like sameObject(x, y) which in that case is supposed to be False.


回答1:


You can use is to check if two objects have the same identity.

>>> x = [1, 2, 3]
>>> y = [1, 2, 3]
>>> x == y
True
>>> x is y
False



回答2:


To build on the answer from Mark Byers:

The is evaluation to distinguish identities will work when the variables contain objects and not primitive types.

object_one = ['d']
object_two = ['d']
assert object_one is object_two  # False - what you want to happen

primitive_one = 'd'
primitive_two = 'd'
assert primitive_one is primitive_two  # True - what you don't want to happen

If you need to compare primitives as well, I'd suggest using the builtin id() function.
From the Python docs:

Return the “identity” of an object. This is an integer which is guaranteed to be unique and constant for this object during its lifetime.

So that will become this:

assert id(primitive_one) == id(primitive_two)  # False


来源:https://stackoverflow.com/questions/3647546/how-do-i-check-if-two-variables-reference-the-same-object-in-python

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!