How to subclass a built-in int type and prevent comparisons

Gabriel Genellina gagsl-py2 at yahoo.com.ar
Sun Mar 2 23:09:13 EST 2008


En Fri, 29 Feb 2008 19:00:06 -0200, Bronner, Gregory  
<gregory.bronner at lehman.com> escribi�:

> I'm trying to create a type-safe subclass of int (SpecialInt) such that
> instances of the class can only be compared with ints, longs, and other
> subclasses of SpecialInt -- I do not want them to be compared with
> floats, bools, or strings, which the native int implementation supports.
>
> Obviously, I could overload __lt_, __eq__, __le__, etc, and write a
> bunch of boilerplate code.
>
> Should this code throw an exception if the types are not comparable?
> What would I lose by doing that?
>
> def __gt__(self, other):
> 		if(other is self):
> 			return False
> 		if(self.__isComparable(other)):
> 			return int(self)>int(other)
> 		else:
> 			raise ValueError(str(self) +" and "+ str(other)
> +" are not comparable")

I think that the easiest way is to write __cmp__ similar to your code  
above, and then redefine __gt__, __ge__ etc based on that.
__gt__ = lambda self, other: self.__cmp__(other)>0

Note that you have to override a lot of methods too; if x is a SpecialInt  
instance, abs(x) or x+1 will return a plain integer instead.

> Is this code likely to be efficient?

Unless you implement the above in a C extension, certainly it will run  
much slower than the original int implementation. But measure how much  
this is going to affect you.

-- 
Gabriel Genellina




More information about the Python-list mailing list