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 ʻis
and==`. Described as a commandment to yourself.
is 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
For example, it is determined whether or not the character strings match even between different objects.
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 ʻis
is 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!')
The if clause is also often used in Python.
if a is not None:
It means that it is different from any of.
If it is better to make an explicit comparison with these,
ʻIf a is not
Make sure you understand the usage and write correct, Pythonic code.