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.
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
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