我對Cython擴展類型(cdef class
)實施了方法__richcmp__
。有些比較案例未定義(例如<
),所以我曾經爲他們提出Exception
,as follows。如果__richcmp__僅部分實現,是否應該引發TypeError?
def __richcmp__(Function self, Function other, op):
if other is None:
eq = False
else:
# guard against mixing managers
assert self.manager == other.manager
eq = (self.node == other.node)
if op == 2:
return eq
elif op == 3:
return not eq
else:
raise TypeError('Only `__eq__` and `__ne__` defined.')
我想pprint
集裝箱這個用Cython類的實例。 pprint
attempts to compare他們,除了TypeError
。我的理解是,TypeError
,pprint
預計未定義__lt__
或不同類型對象的情況(另請參閱Python docs)。
但是,__richcmp__
是實現,因此Python不會引發TypeError
。它叫__richcmp__
,我提出了一個Exception
,這是不會被pprint
忽略。 Cython requires即__richcmp__
被實施,所以我沒有選擇只定義__eq__
和__ne__
。我的代碼改爲TypeError
。看來,如果Python將缺少__lt__
與TypeError
溝通,那麼我應該這樣做,以表示__lt__
不存在,儘管存在整個__richcmp__
,這是使用Cython的副產品,而不是設計意圖。
這個推理是否有意義?我應該提出另一種例外嗎?我在這方面是否正確地解釋了TypeError
的含義?