[Python.NET] Enhancement request: extend __iter__ support to IEnumerator

Greg Chapman glc at well.com
Tue Jul 13 22:33:53 CEST 2004

In the current Python.Net, if you do something which results in an IEnumerator
reference, you cannot use it where Python expects an iterator.  E.g.:

>>> from CLR.System.IO import Directory
>>> files = Directory.GetFiles(".")
>>> list(files.GetEnumerator())
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
TypeError: iteration over non-sequence

Obviously, in the above case it makes more sense to use files directly for
iteration, but a couple of times I've run into methods which return
IEnumerators, and it is annoying not to be able to iterate over them.  It looks
like it would be fairly simple to change ClassBase.tp_iter to check if co.inst
can be cast to IEnumerator, and if so, use that enumerator to initialize the
iterator, e.g. (I haven't tried to compile this):

	public static IntPtr tp_iter(IntPtr ob) {
	    CLRObject co = GetManagedObject(ob) as CLRObject;

	    if (co == null) {
		Exceptions.SetError(Exceptions.TypeError, "invalid object");
		return IntPtr.Zero;

	    IEnumerator enumerator;
	    IEnumerable e = co.inst as IEnumerable;

	    if (e != null)
		enumerator = e.GetEnumerator();
	    else {
		enumerator = co.inst as IEnumerator;
		if (enumerator == null) {
					"iteration over non-sequence"
		    return IntPtr.Zero;

	    Iterator iter = new Iterator(enumerator);
	    return iter.pyHandle;

Greg Chapman

More information about the PythonDotNet mailing list