What is the order of execution of __eq__ if one side inherits from the other? [duplicate]python equality precedenceHow do you remove duplicates from a list whilst preserving order?Python's behavior for rich comparison (Or, when Decimal('100.0') < .01)Override __mul__ from a child class using parent implementation: leads to problemsExtract file name from path, no matter what the os/path format'Queue' object has no attribute 'size'How can I save output tho the same file that I have got the data from, in Python 3Mako: def composition (at render time) not evaluating properlypython decorator for class methodsTrying Python 3 code for this simple Employee object and I'm stuckDelete First Node From Python Linked List

Was murdering a slave illegal in American slavery, and if so, what punishments were given for it?

Separate the element after every 2nd ',' and push into next row in bash

What is this dime sized black bug with white on the segments near Loveland Colorodao?

Department head said that group project may be rejected. How to mitigate?

Expand a hexagon

Difference in 1 user doing 1000 iterations and 1000 users doing 1 iteration in Load testing

How do we properly manage transitions within a descriptive section?

Good examples of "two is easy, three is hard" in computational sciences

How could Dwarves prevent sand from filling up their settlements

If you attack a Tarrasque while swallowed, what AC do you need to beat to hit it?

How to add a low pass filter to this non-inverting amplifier circuit?

How would a physicist explain this starship engine?

1950s or earlier book with electrical currents living on Pluto

Way of refund if scammed?

why "American-born", not "America-born"?

Mikrokosmos, BB 105, Vol. 1: No. 17 Contrary Motion (1) - Can't understand the structure

Warped chessboard

How can sister protect herself from impulse purchases with a credit card?

Existence of a model of ZFC in which the natural numbers are really the natural numbers

Why did Nick Fury not hesitate in blowing up the plane he thought was carrying a nuke?

Schwa-less Polysyllabic German Noun Stems of Germanic Origin

How can I use 400 ASA film in a Leica IIIf, which does not have options higher than 100?

Does a windmilling propeller create more drag than a stopped propeller in an engine out scenario?

Is being an extrovert a necessary condition to be a manager?



What is the order of execution of __eq__ if one side inherits from the other? [duplicate]


python equality precedenceHow do you remove duplicates from a list whilst preserving order?Python's behavior for rich comparison (Or, when Decimal('100.0') < .01)Override __mul__ from a child class using parent implementation: leads to problemsExtract file name from path, no matter what the os/path format'Queue' object has no attribute 'size'How can I save output tho the same file that I have got the data from, in Python 3Mako: def composition (at render time) not evaluating properlypython decorator for class methodsTrying Python 3 code for this simple Employee object and I'm stuckDelete First Node From Python Linked List






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty height:90px;width:728px;box-sizing:border-box;








18
















This question already has an answer here:



  • python equality precedence

    1 answer



I recently stumbled upon a seemingly strange behavior regarding the order in which __eq__ methods are executed, if one side of the comparison is an object which inherits from the other.



I've tried this in Python 3.7.2 in an admittedly academic example. Usually, given an equality comparison a == b, I expect a.__eq__ to be called first, followed by b.__eq__, if the first call returned NotImplemented. However, this doesn't seem to be the case, if a and b are part of the same class hierarchy. Consider the following example:



class A(object):
def __eq__(self, other):
print("Calling A().__eq__".format(self))
return NotImplemented

class B(A):
def __eq__(self, other):
print("Calling B().__eq__".format(self))
return True

class C(object):
def __eq__(self, other):
print("Calling C().__eq__".format(self))
return False

a = A()
b = B()
c = C()

print("a: ".format(a)) # output "a: <__main__.A object at 0x7f8fda95f860>"
print("b: ".format(b)) # output "b: <__main__.B object at 0x7f8fda8bcfd0>"
print("c: ".format(c)) # output "c: <__main__.C object at 0x7f8fda8bcef0>"

a == a # case 1

a == b # case 2.1
b == a # case 2.2

a == c # case 3.1
c == a # case 3.2


In case 1, I expect a.__eq__ to be called twice and this is also what I get:



Calling A(<__main__.A object at 0x7f8fda95f860>).__eq__
Calling A(<__main__.A object at 0x7f8fda95f860>).__eq__


However, in cases 2.1 and 2.2, b.__eq__ is always executed first, no matter on which side of the comparison it stands:



Calling B(<__main__.B object at 0x7f8fda8bcfd0>).__eq__ # case 2.1
Calling B(<__main__.B object at 0x7f8fda8bcfd0>).__eq__ # case 2.2


In cases 3.1 and 3.2 then, the left-hand side is again evaluated first, as I expected:



Calling A(<__main__.A object at 0x7f8fda95f860>).__eq__ # case 3.1
Calling C(<__main__.C object at 0x7f8fda8bcef0>).__eq__ # case 3.1
Calling C(<__main__.C object at 0x7f8fda8bcef0>).__eq__ # case 3.2


It seems that, if the compared objects are related to each other, __eq__ of the object of the child class is always evaluated first. Is there a deeper reasoning behind this behavior? If so, is this documented somewhere? PEP 207 doesn't mention this case, as far as I can see. Or am I maybe missing something obvious here?










share|improve this question















marked as duplicate by user2357112 python
Users with the  python badge can single-handedly close python questions as duplicates and reopen them as needed.

StackExchange.ready(function()
if (StackExchange.options.isMobile) return;

$('.dupe-hammer-message-hover:not(.hover-bound)').each(function()
var $hover = $(this).addClass('hover-bound'),
$msg = $hover.siblings('.dupe-hammer-message');

$hover.hover(
function()
$hover.showInfoMessage('',
messageElement: $msg.clone().show(),
transient: false,
position: my: 'bottom left', at: 'top center', offsetTop: -7 ,
dismissable: false,
relativeToBody: true
);
,
function()
StackExchange.helpers.removeMessages();

);
);
);
May 7 at 20:00


This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.
























    18
















    This question already has an answer here:



    • python equality precedence

      1 answer



    I recently stumbled upon a seemingly strange behavior regarding the order in which __eq__ methods are executed, if one side of the comparison is an object which inherits from the other.



    I've tried this in Python 3.7.2 in an admittedly academic example. Usually, given an equality comparison a == b, I expect a.__eq__ to be called first, followed by b.__eq__, if the first call returned NotImplemented. However, this doesn't seem to be the case, if a and b are part of the same class hierarchy. Consider the following example:



    class A(object):
    def __eq__(self, other):
    print("Calling A().__eq__".format(self))
    return NotImplemented

    class B(A):
    def __eq__(self, other):
    print("Calling B().__eq__".format(self))
    return True

    class C(object):
    def __eq__(self, other):
    print("Calling C().__eq__".format(self))
    return False

    a = A()
    b = B()
    c = C()

    print("a: ".format(a)) # output "a: <__main__.A object at 0x7f8fda95f860>"
    print("b: ".format(b)) # output "b: <__main__.B object at 0x7f8fda8bcfd0>"
    print("c: ".format(c)) # output "c: <__main__.C object at 0x7f8fda8bcef0>"

    a == a # case 1

    a == b # case 2.1
    b == a # case 2.2

    a == c # case 3.1
    c == a # case 3.2


    In case 1, I expect a.__eq__ to be called twice and this is also what I get:



    Calling A(<__main__.A object at 0x7f8fda95f860>).__eq__
    Calling A(<__main__.A object at 0x7f8fda95f860>).__eq__


    However, in cases 2.1 and 2.2, b.__eq__ is always executed first, no matter on which side of the comparison it stands:



    Calling B(<__main__.B object at 0x7f8fda8bcfd0>).__eq__ # case 2.1
    Calling B(<__main__.B object at 0x7f8fda8bcfd0>).__eq__ # case 2.2


    In cases 3.1 and 3.2 then, the left-hand side is again evaluated first, as I expected:



    Calling A(<__main__.A object at 0x7f8fda95f860>).__eq__ # case 3.1
    Calling C(<__main__.C object at 0x7f8fda8bcef0>).__eq__ # case 3.1
    Calling C(<__main__.C object at 0x7f8fda8bcef0>).__eq__ # case 3.2


    It seems that, if the compared objects are related to each other, __eq__ of the object of the child class is always evaluated first. Is there a deeper reasoning behind this behavior? If so, is this documented somewhere? PEP 207 doesn't mention this case, as far as I can see. Or am I maybe missing something obvious here?










    share|improve this question















    marked as duplicate by user2357112 python
    Users with the  python badge can single-handedly close python questions as duplicates and reopen them as needed.

    StackExchange.ready(function()
    if (StackExchange.options.isMobile) return;

    $('.dupe-hammer-message-hover:not(.hover-bound)').each(function()
    var $hover = $(this).addClass('hover-bound'),
    $msg = $hover.siblings('.dupe-hammer-message');

    $hover.hover(
    function()
    $hover.showInfoMessage('',
    messageElement: $msg.clone().show(),
    transient: false,
    position: my: 'bottom left', at: 'top center', offsetTop: -7 ,
    dismissable: false,
    relativeToBody: true
    );
    ,
    function()
    StackExchange.helpers.removeMessages();

    );
    );
    );
    May 7 at 20:00


    This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.




















      18












      18








      18









      This question already has an answer here:



      • python equality precedence

        1 answer



      I recently stumbled upon a seemingly strange behavior regarding the order in which __eq__ methods are executed, if one side of the comparison is an object which inherits from the other.



      I've tried this in Python 3.7.2 in an admittedly academic example. Usually, given an equality comparison a == b, I expect a.__eq__ to be called first, followed by b.__eq__, if the first call returned NotImplemented. However, this doesn't seem to be the case, if a and b are part of the same class hierarchy. Consider the following example:



      class A(object):
      def __eq__(self, other):
      print("Calling A().__eq__".format(self))
      return NotImplemented

      class B(A):
      def __eq__(self, other):
      print("Calling B().__eq__".format(self))
      return True

      class C(object):
      def __eq__(self, other):
      print("Calling C().__eq__".format(self))
      return False

      a = A()
      b = B()
      c = C()

      print("a: ".format(a)) # output "a: <__main__.A object at 0x7f8fda95f860>"
      print("b: ".format(b)) # output "b: <__main__.B object at 0x7f8fda8bcfd0>"
      print("c: ".format(c)) # output "c: <__main__.C object at 0x7f8fda8bcef0>"

      a == a # case 1

      a == b # case 2.1
      b == a # case 2.2

      a == c # case 3.1
      c == a # case 3.2


      In case 1, I expect a.__eq__ to be called twice and this is also what I get:



      Calling A(<__main__.A object at 0x7f8fda95f860>).__eq__
      Calling A(<__main__.A object at 0x7f8fda95f860>).__eq__


      However, in cases 2.1 and 2.2, b.__eq__ is always executed first, no matter on which side of the comparison it stands:



      Calling B(<__main__.B object at 0x7f8fda8bcfd0>).__eq__ # case 2.1
      Calling B(<__main__.B object at 0x7f8fda8bcfd0>).__eq__ # case 2.2


      In cases 3.1 and 3.2 then, the left-hand side is again evaluated first, as I expected:



      Calling A(<__main__.A object at 0x7f8fda95f860>).__eq__ # case 3.1
      Calling C(<__main__.C object at 0x7f8fda8bcef0>).__eq__ # case 3.1
      Calling C(<__main__.C object at 0x7f8fda8bcef0>).__eq__ # case 3.2


      It seems that, if the compared objects are related to each other, __eq__ of the object of the child class is always evaluated first. Is there a deeper reasoning behind this behavior? If so, is this documented somewhere? PEP 207 doesn't mention this case, as far as I can see. Or am I maybe missing something obvious here?










      share|improve this question

















      This question already has an answer here:



      • python equality precedence

        1 answer



      I recently stumbled upon a seemingly strange behavior regarding the order in which __eq__ methods are executed, if one side of the comparison is an object which inherits from the other.



      I've tried this in Python 3.7.2 in an admittedly academic example. Usually, given an equality comparison a == b, I expect a.__eq__ to be called first, followed by b.__eq__, if the first call returned NotImplemented. However, this doesn't seem to be the case, if a and b are part of the same class hierarchy. Consider the following example:



      class A(object):
      def __eq__(self, other):
      print("Calling A().__eq__".format(self))
      return NotImplemented

      class B(A):
      def __eq__(self, other):
      print("Calling B().__eq__".format(self))
      return True

      class C(object):
      def __eq__(self, other):
      print("Calling C().__eq__".format(self))
      return False

      a = A()
      b = B()
      c = C()

      print("a: ".format(a)) # output "a: <__main__.A object at 0x7f8fda95f860>"
      print("b: ".format(b)) # output "b: <__main__.B object at 0x7f8fda8bcfd0>"
      print("c: ".format(c)) # output "c: <__main__.C object at 0x7f8fda8bcef0>"

      a == a # case 1

      a == b # case 2.1
      b == a # case 2.2

      a == c # case 3.1
      c == a # case 3.2


      In case 1, I expect a.__eq__ to be called twice and this is also what I get:



      Calling A(<__main__.A object at 0x7f8fda95f860>).__eq__
      Calling A(<__main__.A object at 0x7f8fda95f860>).__eq__


      However, in cases 2.1 and 2.2, b.__eq__ is always executed first, no matter on which side of the comparison it stands:



      Calling B(<__main__.B object at 0x7f8fda8bcfd0>).__eq__ # case 2.1
      Calling B(<__main__.B object at 0x7f8fda8bcfd0>).__eq__ # case 2.2


      In cases 3.1 and 3.2 then, the left-hand side is again evaluated first, as I expected:



      Calling A(<__main__.A object at 0x7f8fda95f860>).__eq__ # case 3.1
      Calling C(<__main__.C object at 0x7f8fda8bcef0>).__eq__ # case 3.1
      Calling C(<__main__.C object at 0x7f8fda8bcef0>).__eq__ # case 3.2


      It seems that, if the compared objects are related to each other, __eq__ of the object of the child class is always evaluated first. Is there a deeper reasoning behind this behavior? If so, is this documented somewhere? PEP 207 doesn't mention this case, as far as I can see. Or am I maybe missing something obvious here?





      This question already has an answer here:



      • python equality precedence

        1 answer







      python python-3.x






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited May 7 at 16:26









      John Kugelman

      252k55411463




      252k55411463










      asked May 7 at 12:20









      AndreasAndreas

      964




      964




      marked as duplicate by user2357112 python
      Users with the  python badge can single-handedly close python questions as duplicates and reopen them as needed.

      StackExchange.ready(function()
      if (StackExchange.options.isMobile) return;

      $('.dupe-hammer-message-hover:not(.hover-bound)').each(function()
      var $hover = $(this).addClass('hover-bound'),
      $msg = $hover.siblings('.dupe-hammer-message');

      $hover.hover(
      function()
      $hover.showInfoMessage('',
      messageElement: $msg.clone().show(),
      transient: false,
      position: my: 'bottom left', at: 'top center', offsetTop: -7 ,
      dismissable: false,
      relativeToBody: true
      );
      ,
      function()
      StackExchange.helpers.removeMessages();

      );
      );
      );
      May 7 at 20:00


      This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.









      marked as duplicate by user2357112 python
      Users with the  python badge can single-handedly close python questions as duplicates and reopen them as needed.

      StackExchange.ready(function()
      if (StackExchange.options.isMobile) return;

      $('.dupe-hammer-message-hover:not(.hover-bound)').each(function()
      var $hover = $(this).addClass('hover-bound'),
      $msg = $hover.siblings('.dupe-hammer-message');

      $hover.hover(
      function()
      $hover.showInfoMessage('',
      messageElement: $msg.clone().show(),
      transient: false,
      position: my: 'bottom left', at: 'top center', offsetTop: -7 ,
      dismissable: false,
      relativeToBody: true
      );
      ,
      function()
      StackExchange.helpers.removeMessages();

      );
      );
      );
      May 7 at 20:00


      This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.
























          1 Answer
          1






          active

          oldest

          votes


















          18














          From the official documentation for __eq__ :




          If the operands are of different types, and right operand’s type is a direct or indirect subclass of the left operand’s type, the reflected method of the right operand has priority, otherwise the left operand’s method has priority.







          share|improve this answer























          • Thanks for the documentation reference! This doesn't explain the reasoning behind this, though. Are there any drawbacks, if the left operand would always have priority?

            – Andreas
            May 7 at 12:41






          • 2





            Yes, that means that subclasses can't override __eq__ which breaks the abstraction. It would create some very "interesting" polymorphic dispatch if __eq__ would have gotten precedence on the superclass rather than the subclass.

            – Benjamin Gruenbaum
            May 7 at 13:47











          • @BenjaminGruenbaum: Strictly, it could still work if A recognized that B was a subclass and returned NotImplemented... but that would violate Open/Closed because it would require A to explicitly know about and support subclassing, and would require subclasses to override __eq__ whether they want to or not. Overall, a very Bad Thing.

            – Kevin
            May 7 at 16:58

















          1 Answer
          1






          active

          oldest

          votes








          1 Answer
          1






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes









          18














          From the official documentation for __eq__ :




          If the operands are of different types, and right operand’s type is a direct or indirect subclass of the left operand’s type, the reflected method of the right operand has priority, otherwise the left operand’s method has priority.







          share|improve this answer























          • Thanks for the documentation reference! This doesn't explain the reasoning behind this, though. Are there any drawbacks, if the left operand would always have priority?

            – Andreas
            May 7 at 12:41






          • 2





            Yes, that means that subclasses can't override __eq__ which breaks the abstraction. It would create some very "interesting" polymorphic dispatch if __eq__ would have gotten precedence on the superclass rather than the subclass.

            – Benjamin Gruenbaum
            May 7 at 13:47











          • @BenjaminGruenbaum: Strictly, it could still work if A recognized that B was a subclass and returned NotImplemented... but that would violate Open/Closed because it would require A to explicitly know about and support subclassing, and would require subclasses to override __eq__ whether they want to or not. Overall, a very Bad Thing.

            – Kevin
            May 7 at 16:58















          18














          From the official documentation for __eq__ :




          If the operands are of different types, and right operand’s type is a direct or indirect subclass of the left operand’s type, the reflected method of the right operand has priority, otherwise the left operand’s method has priority.







          share|improve this answer























          • Thanks for the documentation reference! This doesn't explain the reasoning behind this, though. Are there any drawbacks, if the left operand would always have priority?

            – Andreas
            May 7 at 12:41






          • 2





            Yes, that means that subclasses can't override __eq__ which breaks the abstraction. It would create some very "interesting" polymorphic dispatch if __eq__ would have gotten precedence on the superclass rather than the subclass.

            – Benjamin Gruenbaum
            May 7 at 13:47











          • @BenjaminGruenbaum: Strictly, it could still work if A recognized that B was a subclass and returned NotImplemented... but that would violate Open/Closed because it would require A to explicitly know about and support subclassing, and would require subclasses to override __eq__ whether they want to or not. Overall, a very Bad Thing.

            – Kevin
            May 7 at 16:58













          18












          18








          18







          From the official documentation for __eq__ :




          If the operands are of different types, and right operand’s type is a direct or indirect subclass of the left operand’s type, the reflected method of the right operand has priority, otherwise the left operand’s method has priority.







          share|improve this answer













          From the official documentation for __eq__ :




          If the operands are of different types, and right operand’s type is a direct or indirect subclass of the left operand’s type, the reflected method of the right operand has priority, otherwise the left operand’s method has priority.








          share|improve this answer












          share|improve this answer



          share|improve this answer










          answered May 7 at 12:25









          LenormjuLenormju

          31414




          31414












          • Thanks for the documentation reference! This doesn't explain the reasoning behind this, though. Are there any drawbacks, if the left operand would always have priority?

            – Andreas
            May 7 at 12:41






          • 2





            Yes, that means that subclasses can't override __eq__ which breaks the abstraction. It would create some very "interesting" polymorphic dispatch if __eq__ would have gotten precedence on the superclass rather than the subclass.

            – Benjamin Gruenbaum
            May 7 at 13:47











          • @BenjaminGruenbaum: Strictly, it could still work if A recognized that B was a subclass and returned NotImplemented... but that would violate Open/Closed because it would require A to explicitly know about and support subclassing, and would require subclasses to override __eq__ whether they want to or not. Overall, a very Bad Thing.

            – Kevin
            May 7 at 16:58

















          • Thanks for the documentation reference! This doesn't explain the reasoning behind this, though. Are there any drawbacks, if the left operand would always have priority?

            – Andreas
            May 7 at 12:41






          • 2





            Yes, that means that subclasses can't override __eq__ which breaks the abstraction. It would create some very "interesting" polymorphic dispatch if __eq__ would have gotten precedence on the superclass rather than the subclass.

            – Benjamin Gruenbaum
            May 7 at 13:47











          • @BenjaminGruenbaum: Strictly, it could still work if A recognized that B was a subclass and returned NotImplemented... but that would violate Open/Closed because it would require A to explicitly know about and support subclassing, and would require subclasses to override __eq__ whether they want to or not. Overall, a very Bad Thing.

            – Kevin
            May 7 at 16:58
















          Thanks for the documentation reference! This doesn't explain the reasoning behind this, though. Are there any drawbacks, if the left operand would always have priority?

          – Andreas
          May 7 at 12:41





          Thanks for the documentation reference! This doesn't explain the reasoning behind this, though. Are there any drawbacks, if the left operand would always have priority?

          – Andreas
          May 7 at 12:41




          2




          2





          Yes, that means that subclasses can't override __eq__ which breaks the abstraction. It would create some very "interesting" polymorphic dispatch if __eq__ would have gotten precedence on the superclass rather than the subclass.

          – Benjamin Gruenbaum
          May 7 at 13:47





          Yes, that means that subclasses can't override __eq__ which breaks the abstraction. It would create some very "interesting" polymorphic dispatch if __eq__ would have gotten precedence on the superclass rather than the subclass.

          – Benjamin Gruenbaum
          May 7 at 13:47













          @BenjaminGruenbaum: Strictly, it could still work if A recognized that B was a subclass and returned NotImplemented... but that would violate Open/Closed because it would require A to explicitly know about and support subclassing, and would require subclasses to override __eq__ whether they want to or not. Overall, a very Bad Thing.

          – Kevin
          May 7 at 16:58





          @BenjaminGruenbaum: Strictly, it could still work if A recognized that B was a subclass and returned NotImplemented... but that would violate Open/Closed because it would require A to explicitly know about and support subclassing, and would require subclasses to override __eq__ whether they want to or not. Overall, a very Bad Thing.

          – Kevin
          May 7 at 16:58





          Popular posts from this blog

          Wikipedia:Vital articles Мазмуну Biography - Өмүр баян Philosophy and psychology - Философия жана психология Religion - Дин Social sciences - Коомдук илимдер Language and literature - Тил жана адабият Science - Илим Technology - Технология Arts and recreation - Искусство жана эс алуу History and geography - Тарых жана география Навигация менюсу

          Bruxelas-Capital Índice Historia | Composición | Situación lingüística | Clima | Cidades irmandadas | Notas | Véxase tamén | Menú de navegacióneO uso das linguas en Bruxelas e a situación do neerlandés"Rexión de Bruxelas Capital"o orixinalSitio da rexiónPáxina de Bruselas no sitio da Oficina de Promoción Turística de Valonia e BruxelasMapa Interactivo da Rexión de Bruxelas-CapitaleeWorldCat332144929079854441105155190212ID28008674080552-90000 0001 0666 3698n94104302ID540940339365017018237

          What should I write in an apology letter, since I have decided not to join a company after accepting an offer letterShould I keep looking after accepting a job offer?What should I do when I've been verbally told I would get an offer letter, but still haven't gotten one after 4 weeks?Do I accept an offer from a company that I am not likely to join?New job hasn't confirmed starting date and I want to give current employer as much notice as possibleHow should I address my manager in my resignation letter?HR delayed background verification, now jobless as resignedNo email communication after accepting a formal written offer. How should I phrase the call?What should I do if after receiving a verbal offer letter I am informed that my written job offer is put on hold due to some internal issues?Should I inform the current employer that I am about to resign within 1-2 weeks since I have signed the offer letter and waiting for visa?What company will do, if I send their offer letter to another company