1

Following is my code snippet. when i run the program it gives me the following error.

 @functools.total_ordering
 AttributeError: 'module' object has no attribute 'total_ordering'

I'm using python 3.1

import functools

@functools.total_ordering
class Abs(object):
    def __init__(self,num):
        self.num=abs(num)
    def __eq__(self,other):
        return self.num==abs(other.num)
    def __lt__(self,other):
        return self.num < abs(other.num)

five=Abs(-5)
four=Abs(-4)
print(five > four)

Is something missing from the import statement ?

Tharanga Abeyseela
  • 3,255
  • 4
  • 33
  • 45

1 Answers1

2

No, your import statement is fine. The problem is that your Python installation is one version behind. functools.total_ordering was added in Python 3.2. From the docs:

New in version 3.2.

Changed in version 3.4: Returning NotImplemented from the underlying comparison function for unrecognized types is now supported.

So, you will need to upgarde in order to use it. If that is not possible, then you will just have to define all of the comparison operators manually.

Note that this decorator was also backported to Python 2.7, but I assume that you want to keep with Python 3.x.

  • I can see the total_ordering in here also https://docs.python.org/2/library/functools.html – Tharanga Abeyseela Dec 18 '14 at 03:06
  • 1
    Well, yes. `total_ordering` was backported to Python 2.7. So, you could use that version if you want. Remember that Python 3.1 came out before 2.7 became what it is today. The Python community is basically split right now. Some are developing for 2.7 while others are moving on to 3.5. :) –  Dec 18 '14 at 03:07
  • upgraded to 2.7.9 but it is giving me a different error now. File "./1.py", line 14, in x=(five > four) File "/usr/local/lib/python2.7/functools.py", line 56, in '__lt__': [('__gt__', lambda self, other: not (self < other or self == other)), File "./1.py", line 10, in __lt__ return self.num < abs(other) TypeError: bad operand type for abs(): 'Abs' – Tharanga Abeyseela Dec 18 '14 at 03:35
  • Python currently doesn't know what to do when you give an `Abs` instance to `abs()`. It looks like you should be doing `abs(other.num)` in your comparison methods. Otherwise, you will need to overload `__abs__` to tell Python what you want to do when `abs()` is used on your class. –  Dec 18 '14 at 03:39