[IronPython] Writing a Python iterator in C#?

Dino Viehland dinov at microsoft.com
Sat May 1 00:19:23 CEST 2010


Jeff wrote:
> I'm trying to implement a Python iterator in C# without also
> implementing IEnumerator/IEnumerable (I'm also assuming it's even
> possible, of course). When trying to use the class in a for loop (`cu`
> is a Cursor instance):
> 
> >>> for row in cu:
> ....      print cu
> 
> TypeError: Unable to cast object of type 'Cursor' to type
> 'IronPython.Runtime.Types.IPythonObject'.

That's definitely a bug.  We usually check for the interfaces first and
we have a code path that's assuming we have a user-defined object when
we're not an enumerable/enumerator but we have __iter__.  It's easy
enough to fix we're just trying to generate optimal code for getting
the Python type of an object.


Is there a reason you can't implement IEnumerator/IEnumerable?   You can 
Always implement it explicitly like:

IEnumerator IEnumerable.GetEnumerator()  {
}

If having the public surface area is an issue.  Or you could mark the
methods w/ [PythonHidden] attribute.

> 
> I've got the necessary methods on the class (__iter__() and next())
> and I've marked the class with [PythonType]; is there anything else
> that needs to be done?





More information about the Ironpython-users mailing list