I've only been in Python for about a year now, but I've noticed that I couldn't clearly distinguish between the comparison operators ʻisand
==`. Described as a commandment to yourself.
ʻIsis Object Identity
==` is Object Equality
Is. As the name implies, Object Identity determines whether they are the same object.
On the other hand, for ==
, it is the same implementation as the __eq__
method.
For example, it is determined whether or not the character strings match even between different objects.
https://docs.python.org/3/reference/datamodel.html#object.eq
a = 'hoge'
print(a.__eq__('hoge')) # True
a = None
if a == None:
print('Not good')
On the other hand, if it complies with PEP8, the following will be alerted.
E711 comparison to None should be 'if cond is Nond:'
This says that for singletons like None, identity in Object Identity should be compared. Therefore, it is desirable to write as follows.
a = None
if a is None:
print('Good')
However, if it is not necessary to clearly indicate that it is None, ↓ is Pythonic. (3. I wrote it in a digression)
a = None
if not a:
print('Good')
Also, for example, if ʻisis used for character string comparison as shown below, it cannot be evaluated properly. If you want to make a comparison such as strings match, you need to use
==`.
(Also, in the case of string comparison, you should also be careful about unicode or str)
a = 'hoghoge'
if a is 'hogehoge':
print('This is not called!')
else:
print('This is called!')
if a:
The if clause is also often used in Python.
this is,
if a is not None:
Unlike a,
False
[]
None
''
0
It means that it is different from any of.
If it is better to make an explicit comparison with these,
ʻIf a is not
If not,
if a:
OK.
Make sure you understand the usage and write correct, Pythonic code.
Recommended Posts