python - Total_ordering and class inheritance -


from understand, total_ordering decorator functools not expected work nicely classes inherited ordered class: doesn't try define comparison functions because defined.

see example:

from functools import total_ordering collections import namedtuple  test = namedtuple('test',['a','b'])  @total_ordering class testord(test):     def __lt__(self,other):         return self.b < other.b or self.b == other.b , self.a < other.a  x = testord(a=1,b=2) y = testord(a=2,b=1) print(x < y)   # expected: false print(x <= y)  #           false print(x > y)   #           true print(x >= y)  #           true print(y < x)   #           true print(y <= x)  #           true print(y > x)   #           false print(y >= x)  #           false 

of tests, ones involving < operator give expected result.

i can > ones work adding __gt__ = lambda *_ : notimplemented class definition. on other hand, if add similar definitions __le__ or __ge__, corresponding tests fail (for __le__):

typeerror: unorderable types: testord() <= testord() 

which leads me believe not proper way address problem.

hence question: is there proper way reorder class total_ordering?

(yes, know doing total_ordering's job hand trivial, , know example, defining unordered namedtuple trivial too.)

for example, solve problem introducing additional base class not directly inherit test:

test = namedtuple('test',['a','b'])  @total_ordering class testordbase:     def __lt__(self ,other):         return self.b < other.b or self.b == other.b , self.a < other.a  class testord(testordbase, test):     pass 

the order of base classes testord important, testordbase must come before test.


Comments

Popular posts from this blog

html - Outlook 2010 Anchor (url/address/link) -

javascript - Why does running this loop 9 times take 100x longer than running it 8 times? -

Getting gateway time-out Rails app with Nginx + Puma running on Digital Ocean -