Using COM objects as dictionaries in win32com.
I've often been irritated that the [] notation doesn't work consistently on
COM objects that can be viewed as some sort of mapping containers. In my
experience you must use: () to read from the collection and [] to write to
it.
With just a bit of testing the following modification to dynamic.py SEEMS to
make the notation more consistent. I can for instance use the Session and
Request objects under ASP in a lot more natural way.
The only thing I've done is to put the code using _NewEnum() inside:
if isinstance(index, IntType): so that [] uses the Item method instead of
the enumerator when you pass in anything but IntType objects.
I suppose there might be good reasons for not applying this patch, but it be
cool to know why.
Modified version:
def __getitem__(self, index): # syver modified
# Much check _NewEnum before Item, to ensure b/w compat.
if isinstance(index, IntType):
if self.__dict__['_enum_'] is None:
self.__dict__['_enum_'] = self._NewEnum()
if self.__dict__['_enum_'] is not None:
return
self._get_good_object_(self._enum_.__getitem__(index))
# See if we have an "Item" method/property we can use (goes hand in
hand with Count() above!)
invkind, dispid = self._find_dispatch_type_("Item")
if invkind is not None:
return self._get_good_object_(self._oleobj_.Invoke(dispid, LCID,
invkind, 1, index))
raise TypeError, "This object does not support enumeration"
Original version
def __getitem__(self, index):
# Much check _NewEnum before Item, to ensure b/w compat.
if self.__dict__['_enum_'] is None:
self.__dict__['_enum_'] = self._NewEnum()
if self.__dict__['_enum_'] is not None:
return self._get_good_object_(self._enum_.__getitem__(index))
# See if we have an "Item" method/property we can use (goes hand in
hand with Count() above!)
invkind, dispid = self._find_dispatch_type_("Item")
if invkind is not None:
return self._get_good_object_(self._oleobj_.Invoke(dispid, LCID,
invkind, 1, index))
raise TypeError, "This object does not support enumeration"