Menu

#715 Indexing of objects with Items broken

v1.0 (example)
open
nobody
None
5
2016-03-04
2016-03-04
Braino
No

As I read in several places, Objects with the Item() method like should map indexing obj[i] to obj.Item(i).

The problem is: It just does not work for me. After running makepy for the Word 14 Object Library, using

import win32com.client

app = win32com.client.Dispatch("Word.Application")

app.Dialogs.Item(1)  # Succeeds and returns a Library.Dialog Object

app.Dialogs[1]  # Type Error: 'Dialogs' object does not support indexing

I dug deeper and I found that there is indeed no getitem method in the corresponding class created by makepy. The code responsible I identified in the genpy file is:

def WriteClassBody(self, generator):
    ...
    specialItems = {..., "item"=None, ...}
    for name in names:
        ...
        if dispid==pythoncom.DISPID_VALUE:
            lkey = "value"
        ...
        else:
            lkey = name.lower()

        if lkey in specialItems and specialItems[lkey] is None:
            specialItems[lkey] = (entry, ...)

So in principle, it should recognize "item" as special item and remember that it has been there (later there is a section in the code where it checks if "item" was there and adds a getitem method if it was). The problem is that dispid for "item" is actually equal to pythoncom.DISPID_VALUE and therefore the lkey is set to "value" which is not special anymore. You can easily verify that by changing "if dispid==pythoncom.DISPID_VALUE:" to "if dispid==pythoncom.DISPID_VALUE and name.lower() != "item":" and running makepy again; the getitem methods are created and indexing works as it should.

Discussion

Want the latest updates on software, tech news, and AI?
Get latest updates about software, tech news, and AI from SourceForge directly in your inbox once a month.