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

Antonio Cuni anto.cuni at gmail.com
Tue Dec 4 10:52:02 CET 2007

amit wrote:
> Taking example of System.Collection.ArrayList  class.
> If the class uses the interface IEnumerable that can be checked using 
> reflection  
>     b_type = System.Type.GetType(fullname)
>     ifaces = b_type.GetInterfaces()
>     for interface in ifaces:
>     if interface =="IEnumerable":
>             print "yes"
> 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()

To summarize:

   - for classes implementing IEnumerable: you should map __iter__ to 

   - for classes implementing IEnumerator: you should add a next() 
method like the one above, and add an __iter__ that returns self.

> 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 had in mind something like
>     class Dummy:
>     __iter__(self):
>        return CS.Current()
>     next(self):
>        bool = CS.MoveNext()
>        if bool == false:
>         raise StopIteration

this is also a good solution; you should remind to return 
CS.get_Current() at the end of next().
One thing I don't understand: what is CS?

ciao Anto

More information about the Pypy-dev mailing list