Called by comparison operations. Should return a negative integer if self < other, zero if self == other, a positive integer if self > other. Networks with different prefixlen are considered non-equal. Networks with the same prefixlen and differing addresses are
(self, other)
| 631 | |
| 632 | |
| 633 | def __cmp__(self, other): |
| 634 | """Called by comparison operations. |
| 635 | |
| 636 | Should return a negative integer if self < other, zero if self |
| 637 | == other, a positive integer if self > other. |
| 638 | |
| 639 | Networks with different prefixlen are considered non-equal. |
| 640 | Networks with the same prefixlen and differing addresses are |
| 641 | considered non equal but are compared by their base address |
| 642 | integer value to aid sorting of IP objects. |
| 643 | |
| 644 | The version of Objects is not put into consideration. |
| 645 | |
| 646 | >>> IP('10.0.0.0/24') > IP('10.0.0.0') |
| 647 | 1 |
| 648 | >>> IP('10.0.0.0/24') < IP('10.0.0.0') |
| 649 | 0 |
| 650 | >>> IP('10.0.0.0/24') < IP('12.0.0.0/24') |
| 651 | 1 |
| 652 | >>> IP('10.0.0.0/24') > IP('12.0.0.0/24') |
| 653 | 0 |
| 654 | |
| 655 | """ |
| 656 | |
| 657 | # Im not really sure if this is "the right thing to do" |
| 658 | if self._prefixlen < other.prefixlen(): |
| 659 | return (other.prefixlen() - self._prefixlen) |
| 660 | elif self._prefixlen > other.prefixlen(): |
| 661 | |
| 662 | # Fixed bySamuel Krempp <krempp@crans.ens-cachan.fr>: |
| 663 | |
| 664 | # The bug is quite obvious really (as 99% bugs are once |
| 665 | # spotted, isn't it ? ;-) Because of precedence of |
| 666 | # multiplication by -1 over the substraction, prefixlen |
| 667 | # differences were causing the __cmp__ function to always |
| 668 | # return positive numbers, thus the function was failing |
| 669 | # the basic assumptions for a __cmp__ function. |
| 670 | |
| 671 | # Namely we could have (a > b AND b > a), when the |
| 672 | # prefixlen of a and b are different. (eg let |
| 673 | # a=IP("1.0.0.0/24"); b=IP("2.0.0.0/16");) thus, anything |
| 674 | # could happen when launching a sort algorithm.. |
| 675 | # everything's in order with the trivial, attached patch. |
| 676 | |
| 677 | return (self._prefixlen - other.prefixlen()) * -1 |
| 678 | else: |
| 679 | if self.ip < other.ip: |
| 680 | return -1 |
| 681 | elif self.ip > other.ip: |
| 682 | return 1 |
| 683 | elif self._ipversion != other._ipversion: |
| 684 | # IP('0.0.0.0'), IP('::/0') |
| 685 | return cmp(self._ipversion, other._ipversion) |
| 686 | else: |
| 687 | return 0 |
| 688 | |
| 689 | |
| 690 | def __hash__(self): |