Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Operator is in Python #32

Open
selfboot opened this issue Jun 22, 2017 · 0 comments
Open

Operator is in Python #32

selfboot opened this issue Jun 22, 2017 · 0 comments
Labels

Comments

@selfboot
Copy link
Owner

selfboot commented Jun 22, 2017

From the documentation for the is operator:

The operators is and is not test for object identity: x is y is true if and only if x and y are the same object.

We can use id(object) to get 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. CPython implementation detail: This is the address of the object in memory.

And so the following are equivalent.

>>> a is b
>>> id(a) == id(b)

Remember: do not use is to compare integers. Look at the following demo:

>>> a = 257
>>> b = 257
>>> a is b
False

This is because every time you define an object in Python, you'll create a new object with a new identity. But there are some exceptions for small integers and small strings.

>>> b = 256
>>> a = 256
>>> a is b
True

From doc, we know in CPython:

The current implementation keeps an array of integer objects for all integers between -5 and 256, when you create an int in that range you actually just get back a reference to the existing object.

For more strange things about is, you can read Understanding Python's “is” operator, then you can understand:

>>> x = 'a' 
>>> x += 'bc'
>>> y = 'abc'
>>> x is y
False
>>> a = 0
>>> a += 1
>>> b = 1
>>> a is b
True
>>> z = 'abc'
>>> w = 'abc'
>>> z is w
True

More worse, you may be stuck by the following code:

>>> def func():
...     a = 1000
...     b = 1000
...     return a is b
...
>>> a = 1000
>>> b = 1000
>>> a is b, func()
(False, True)

Don't worry, you can find a detailed explantation here.

Ref
What does id( ) function used for?
Two variables in Python have same id, but not lists or tuples
'is' operator behaves unexpectedly with non-cached integers
“is” operator behaves unexpectedly with integers
Understanding Python's “is” operator

@selfboot selfboot changed the title Operator is VS == Operator is in Python Jun 22, 2017
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

1 participant