[python-win32] Trouble with list iteration / comprehension for wrapped COM objects

dornech dornech at gmx.de
Fri Apr 18 20:33:01 EDT 2025


Hi there,

I am working on an EXCEL wrapper to "phytonize" access to EXCEL.

I create a wrapper class for all objects classes derived from abasic 
wrapper class which mainly ensures that calls are snaked-case and 
pyhtonized calls work. I. e. workbokkobject.SaveAs, 
workbookobject.saveas and workbokkobject.save_as would all work. This is 
done by overloaded __getattr__ and __setattr__ methods.

The "real" EXCEL object is stored in the attribute "_xlWrapped".

The overloaded __getattr__ also ensures that when retrieving f. e. a 
workbook from the application wrapper, that the resulting EXCEL object 
is wrapped as well. I. e. let xlapp be my wrapped EXCEL then 
xlapp.active_workbook would return a reference to a wrapped Workbook 
object which contains the reference to the "real" EXCEL workbook object 
in the attribute _xlwrapped.

I also overload __getitem__ to allow xlapp[1] as short for 
xlapp.workbooks(1).

Some of these classes I do extend for example to check existence of a 
worksheet in a workbook.

This as very brief introduction.

Now I am struggeling with list comprehension and indexes.

     # access un-wrapped EXCEL
     print(xlapp._xlWrapped.Workbooks(1).Name)
     print(xlapp._xlWrapped.Workbooks(2).Name)
     for i, wb in enumerate(xlapp._xlWrapped.Workbooks):
         print(i, wb.Name)

     # access wrapped EXCEL
     print(xlapp.Workbooks(1).Name)
     print(xlapp.Workbooks(2).Name)
     for i, wb in enumerate(xlapp.Workbooks):
         print(i, wb.Name)

This prints
     WB1.xls
     WB2.xls
     0  WB1.xls
     1  WB2.xls
     WB1.xls
     WB2.xls
  and aborts with an windows/COM error:

  ret = self._oleobj_.InvokeTypes(170, LCID, 2, (13, 0), ((12, 1),),Index
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
pywintypes.com_error: (-2147352567, 'Ausnahmefehler aufgetreten.', (0, 
None, None, None, 0, -2147352565), None)

Obviously when looping via the wrapper object the index is not 
automatically adjusted.
However, I must not increase the index by on in __getitem__ because then 
the index would alway be increased.

It seems, püywin32 has some special support for list comprehension and 
index adjustment for COM objects?
I haven't worked with an iterator before but is this the solution?

Thanks in advance.

Best
Christoph







More information about the python-win32 mailing list