Python COM iterator

Larry Bates larry.bates at websafe.com
Wed Apr 18 19:38:03 EDT 2007


Carsten Haese wrote:
> On Tue, 2007-04-17 at 16:54 -0500, Larry Bates wrote:
>> Does anyone know if there is a way to make a Python COM object
>> act like a proper iterator in VB/Delphi?
> 
> I don't use COM, VB, or Delphi, but Google turned up these two
> references:
> http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcn7/html/vaconUsingForEach.asp  http://17slon.com/blogs/gabr/2007/03/fun-with-enumerators-part-1.html
> 
> Judging from those links, an object is iterable in VB and Delphi (or as
> they call it, it is enumerable) if it exposes a GetEnumerator method
> that returns an enumerator. The enumerator in turn needs to expose a
> MoveNext method and a Current property.
> 
> Assuming that the Enumerable and the Enumerator are allowed to be the
> same object, you'll probably need code that looks something like this:
> 
>   class foo:
>     _public_methods_=['GetEnumerator','MoveNext']
>     # You'll need to figure out how to expose "self.Current"
> 
>     def __init__(self):
>         self.numbers=[1,2,3,4,5,6,7,8]
>         self.Current = None
> 
>     def MoveNext(self):
>         try:
>             self.Current = self.numbers.pop(0)
>             return True
>         except IndexError:
>             return False
> 
>     def GetEnumerator(self):
>         return self
> 
> Good luck,
> 
> Carsten.
> 
> 

I looked over the links and what you have proposed seems to make sense, but
I can't make it work.  I have the following class defined and registered.

class foo:

    _public_methods_=['GetEnumerator','MoveNext']
    _public_attrs_=['Current']
    _reg_clsid_='{FC2A0E7B-E428-4414-B1C4-60373BB12102}'
    _reg_progid_="Syscon.foo"

    def __init__(self):
        self.numbers=[1,2,3,4,5,6,7,8]
        self.Current = None

    def MoveNext(self):
        try:
            self.Current = self.numbers.pop(0)
            rtnval=True

        except IndexError:
            self.Current=None
            rtnval=False

    def GetEnumerator(self):
        return self


Then I do:

>>> import win32com.client
>>> typelib='Syscon.foo'
>>> F=win32com.client.Dispatch(typelib)
>>> for x in F:
... 	print x
... 	
Traceback (most recent call last):
  File "<interactive input>", line 1, in <module>
  File "C:\Python25\lib\site-packages\win32com\client\dynamic.py", line 228, in
__getitem__
    raise TypeError, "This object does not support enumeration"
TypeError: This object does not support enumeration
>>>

but this works fine:

>>> F.MoveNext()
>>> F.Current
1
>>> F.MoveNext()
>>> F.Current
2
>>>


I'm stumped.

-Larry



More information about the Python-list mailing list