[pypy-dev] mapping C# iterator to Python iterator

amit regmi.amit at gmail.com
Tue Dec 4 16:05:22 CET 2007

Antonio Cuni wrote:
> amit wrote:
>> Problems mapping the two functions
>>     d['__iter__'] = d['GetEnumerator']
>>     d['next'] = d['MoveNext']
>> to make C# objects iterable in PyPy-Cli module.
>> a) MoveNext() is not available in both "methods" and "staticmethods" 
>> passed to build_wrapper
> sure, that's expected. MoveNext() is a method defined for the 
> IEnumerator interface, not for IEnumerable.
> Moreover, I just realized that there is a discrepancy between .NET's 
> MoveNext() and Python's next() methods: the former only advances the 
> iterator without returning the current object, while the latter both 
> advances the iterator and returns the current objects; also, we should 
> throw StopIterationError when we reach the end of the iterator. In 
> other words, next() should be implemented this way:
> def next(self):
>     if not self.MoveNext():
>         raise StopIterationError
>     return self.get_Current()
This makes a lot of sense. I think what you mean is
    self.enumrator = self.GetEnumerator()     # this returns IEnumerator
    def next(self):
           if not self.enumrator.MoveNext()
                   raise StopIteration
           return self.enumrator.Current()         #  or  self.get_Current()

but MoveNext() can not be called this way. I have tried it. And MoveNext 
is not available to self as your example shows.

> To summarize:
>   - for classes implementing IEnumerable: you should map __iter__ to 
> GetEnumerator
>   - for classes implementing IEnumerator: you should add a next() 
> method like the one above, and add an __iter__ that returns self.
I think classes only implement IEnumerable. and IEnumerable uses 
IEnumerator as below:

public interface IEnumerable
    IEnumerator GetEnumerator();

>> b) and assignment of GetEnumerator to __iter__ gives following 
>> TypeError.
>>     TypeError: Can't convert object 
>> System.Collections.ArrayList+SimpleEnumerator to Python
> could you check in a failing test please?
I have checked in failing test in test_clr.py

- AmitReg

More information about the Pypy-dev mailing list