Python COM iterator

Larry Bates larry.bates at websafe.com
Thu Apr 19 12:39:50 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?
>> [...]
> 
> After more googling, staring at win32com's code, and a fair bit of trial
> and error, I've come up with the following working example:
> 
> # server.py
> import pythoncom
> 
> class HelloWorld:
>     _reg_clsid_ = "{CAB8BED1-9174-4AAD-ABC5-F377951CB71B}"
>     _reg_desc_ = "Python Test COM Server"
>     _reg_progid_ = "Python.TestServer"
>     _public_methods_ = ['Next']
>     _com_interfaces_ = [pythoncom.IID_IEnumVARIANT]
>     
>     def __init__(self):
>         self.numbers=[1,2,3,4,5,6,7,8]
> 
>     def Next(self, count):
>         assert count==1
>         try:
>             return (self.numbers.pop(0),)
>         except IndexError:
>             return ()
>     
>     def _NewEnum(self):
>         import win32com.server.util
>         return win32com.server.util.wrap(self)
> 
> if __name__=='__main__':
>   import win32com.server.register 
>   win32com.server.register.UseCommandLine(HelloWorld)
>   
> # client.py
> import win32com.client
> comobj = win32com.client.Dispatch("Python.TestServer")
> for x in comobj:
>     print x
> 
> This works for me on Python 2.5 and pywin32 Build 210, but I don't know
> whether clients in VB or Delphi are able to use this iterator.
> 
> -Carsten
> 
> 

I tested in VB and by golly it works!  What is odd is that this looks
NOTHING like what we got from the docs earlier.  No GetEnumerator
method, no MoveNext method.  I'm glad it works, but I'm a little
puzzled as to why it works.

Thanks loads.

-Larry



More information about the Python-list mailing list