Usefulness of subclassing builtin number types

David Abrahams dave at boost-consulting.com
Sun Dec 15 12:47:03 EST 2002


Gerhard Häring <gerhard.haering at gmx.de> writes:

> I'd like to subclass some builtin number types, and int in particular.
> And I want (of course) that this subclassing is 'sticky', so if I do a:
>
>     x = MyInt(25)
>     x *= 2
>
> I want 'x' to stay of the class MyInt. I even can't think of any use
> case right now where I'd *not* want this. The problem? Python doesn't do
> this, instead it always returns ints.

Boost.Python currently uses an Int subclass for wrapping C++ enums.  We
like the behavior that x * 2 is an Int, not an object of the wrapped
enum type, because it mirrors the C++ behavior.  You have to
explicitly cast back to an object of the enumeration type to get
there.

<snip>

>     # Behaviour of superclass is ok for __truediv__, __complex__, __int__,
>     # __long__, __float__, __oct__, __hex__, __cmp__, __str__, __repr__
>
> class MyInt(StickyInt):
>     pass
>
> if __name__ == "__main__":
>     x = MyInt(25000)
>     x = abs(x + 1)
>     print type(x), x
> print x+1
> #v-
>
> ... which is a little *cough* more verbose than I'd want it to be. 

I see your point.

This is a sticky one.  I wonder what Guido thinks?

-- 
                       David Abrahams
   dave at boost-consulting.com * http://www.boost-consulting.com
Boost support, enhancements, training, and commercial distribution



More information about the Python-list mailing list