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


Groups > comp.lang.python > #45211 > unrolled thread

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

Started byNed Batchelder <ned@nedbatchelder.com>
First post2013-05-12 19:35 -0400
Last post2013-05-12 19:35 -0400
Articles 1 — 1 participant

Back to article view | Back to comp.lang.python

This discussion starts older than the indexed window; earlier articles aren't shown. The article labeled Started by below is the oldest one visible, not the original post.


Contents

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

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

FromNed Batchelder <ned@nedbatchelder.com>
Date2013-05-12 19:35 -0400
SubjectRe: Differences of "!=" operator behavior in python3 and python2 [ bug? ]
Message-ID<mailman.1604.1368401743.3114.python-list@python.org>
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

[toc] | [standalone]


Back to top | Article view | comp.lang.python


csiph-web