Is there a substantial difference in Python 3.x between:
for each_line in data_file:
if each_line.find(\":\") != -1:
#placeholder for code
Different rich comparison methods are called depending on whether you use ==
or !=
.
class EqTest(object):
def __eq__(self, other):
print "eq"
return True
def __ne__(self, other):
print "ne"
return False
a = EqTest()
b = EqTest()
print not (a == b)
# eq
# False
print a != b
# ne
# False
As far as I know, you will get the same result for all built-in types, but theoretically they could have different implementations for some user-defined objects.
I would use !=
instead of not
and ==
simply because it is one operation instead of two.
Your first example is how you should be testing the result of find
.
Your second example is doing too much. It is additionally performing a boolean not on the result of the each_line.find(":") == -1
expression.
In this context, where you want to use not
is when you have something that you can test for truthiness or falsiness.
For example, the empty string ''
evaluates to False:
s = ''
if not s:
print('s is the empty string')
You seem to be conflating a little bit the identity-test expressions is
and is not
with the boolean not
.
An example of how you'd perform an identity test:
result_of_comparison = each_line.find(":") == -1
if result_of_comparison is False: # alternatively: is not True
pass
As I understand it,
functionally they are not entirely the same; if you are comparing against a class, the class could have a member function, __ne__
which is called when using the comparison operator !=, as opposed to __eq__
which is called when using the comparison ==
So, in this instance,
not (a == b)
would call __eq__
on a, with b as the argument, then not
the result
(a != b)
would call __ne__
on a, with b as the argument.
I would use the first method (using !=) for comparison