Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #45211

Re: Differences of "!=" operator behavior in python3 and python2 [ bug? ]

Date 2013-05-12 19:35 -0400
From Ned Batchelder <ned@nedbatchelder.com>
Subject Re: Differences of "!=" operator behavior in python3 and python2 [ bug? ]
References <CAJxoosfPri76e+Zp802a3Ve5d9aY5Mrav0VLwU64bxJt1bZDag@mail.gmail.com>
Newsgroups comp.lang.python
Message-ID <mailman.1604.1368401743.3114.python-list@python.org> (permalink)

Show all headers | View raw


On 5/12/2013 7:23 PM, Mr. Joe wrote:
> I seem to stumble upon a situation where "!=" operator misbehaves in
> python2.x. Not sure if it's my misunderstanding or a bug in python
> implementation. Here's a demo code to reproduce the behavior -
> """
> # -*- coding: utf-8 -*-
> from __future__ import unicode_literals, print_function
>
> class DemoClass(object):
>      def __init__(self, val):
>          self.val = val
>
>      def __eq__(self, other):
>          return self.val == other.val
>
> x = DemoClass('a')
> y = DemoClass('a')
>
> print("x == y: {0}".format(x == y))
> print("x != y: {0}".format(x != y))
> print("not x == y: {0}".format(not x == y))
> """
>
> In python3, the output is as expected:
> """
> x == y: True
> x != y: False
> not x == y: False
> """

In Python 3, if __ne__ isn't defined, "!=" will call __eq__ and negate 
the result.
> In python2.7.3, the output is:
> """
> x == y: True
> x != y: True
> not x == y: False
> """
> Which is not correct!!

In Python 2, "!=" only calls __ne__.  Since you don't have one defined, 
it's using the built-in object comparison, and since x and y are 
different objects, they are not equal to each other, so x != y is True.

> Thanks in advance for clarifications.
> Regards,
> TB

Back to comp.lang.python | Previous | Next | Find similar | Unroll thread


Thread

Re: Differences of "!=" operator behavior in python3 and python2 [ bug? ] Ned Batchelder <ned@nedbatchelder.com> - 2013-05-12 19:35 -0400

csiph-web