class semantics

Mark Lutz (mlutz@KaPRE.COM)
Thu, 2 Feb 1995 14:06:58 +0700

Here's another one of those "How come we can't" mails you
love so much :-)

I've been playing with the new class operator-overloading
stuff. Looks great in general. I'm trying to wrap a C++
instance in a Python class, and let it be used in whatever
context is appropriate. My C++ framework lets me access
members by name dynamically, and do type testing on the fly;
I don't need type signatures (or code generation) in advance.

Now, operators help for expressions:

x = CxxThing(ptr-to-a-c++-instance)
x[99] # __getitem__
x = 99, 99 + x, x + y # __add__, __radd__

but things like:

for i in range(x): ...
list[x] ...

don't work, because they don't try to coerce the instance
to an integer first: __coerce__ doesn't get called [but it
probably shouldn't, since it seems to be intended to convert
an operand UP to the class's type, before an operator is
applied], and neither does __int__.

It's probably a lot of work, but it would be neat if the
interpreter allowed instance objects wherever integers
(intobject's) were required, and called __coerce__ (or
something similar) if present:

class CxxThing:
def __convert__(self, type): # on range, [x], ..
if type == IntType:
return self.asInteger()
else:
return None

Then class instances could really look like integers
everywhere. This is how C++ does (some) type conversions.

I know I could force class users to do an explicit "int(x)"
in case the item is an instance, but that's a bit non-seamless.
An extension data-type (rather than a class wrapper) won't
work here either, since the interpreter really wants an
"intobject" in these places.

Make any sense? Obviously a bit of work--off the top of my
head, there's indexing, slicing, range, getargs [pause...];
grep shows a lot more places too! Performance impact isn't
clear...

This is potentially a broader issue than integer conversion too--
in fact, it would be great if instances were allowed everywhere
a specific data type is required. Just dreaming, :-)

Mark L.

ps: BTW, Tkpython is really quite cool!

pps: Feel free to copy this to the list if you think it's of
general interest; didn't want to open another feature thread...