Enhancement request: extend __iter__ support to IEnumerator
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): [CallConvCdecl()] 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) { Exceptions.SetError(Exceptions.TypeError, "iteration over non-sequence" ); return IntPtr.Zero; } } Iterator iter = new Iterator(enumerator); return iter.pyHandle; } --- Greg Chapman
participants (1)
-
Greg Chapman