selfboot / AnnotatedShadowSocks

Annotated shadowsocks(python version)
Other
3 stars 1 forks source link

Operator is in Python #32

Open selfboot opened 7 years ago

selfboot commented 7 years ago

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