[python-win32] "Casting" COM objects

Paul Prescod paul@prescod.net
Mon, 07 Apr 2003 17:51:44 -0700


Mark Hammond wrote:
> I think you are looking for the (fairly new) win32com.client.CastTo()
>...
> 
> I *think* that is what you were asking :)

Exatly. It is so new that my copy of pythonwin doesn't have it. But 
that's not a big deal, my workaround is good enough for now and I'll use 
this when the time comes.

But over time, my question changed. It became: "how can I get dynamic 
behaviour out of a makepy'd class." One suggestion is that MakePy's 
__getattr__ could fall back to trying to do a dynamic dispatch. If 
you're going to raise an exception anyhow, you might as well be sure 
that the thing you're trying to do is going to fail. The downside of 
this is that it might allow people to inefficiently call methods that 
are missing in the static interface and not know why it is so slow. Case 
errors in particular might be worrisome.

So perhaps we would add a keyword parameter to the MakePy class: 
"dynamicfallback = true". Once you turn this on, you get the convenience 
of dynamic dispatch but you may lose some performance when the static 
method isn't available.

Another strategy might be to have a method called AsDynamic() or 
AsDispatch() that allows you to call methods that aren't in the 
statically generated interface. e.g.

foo = bar.AsDynamic().bar()

Except for the performance, I prefer all of these to CastTo (just a 
little) because they feel more like programming in Python (dynamic, 
performance is secondary) than like programming in Java (static, with 
type declarations and casts to ensure high performance).

  Paul Prescod