@@ -6,30 +6,47 @@ namespace Python.Runtime.CollectionWrappers
66{
77 internal class IterableWrapper < T > : IEnumerable < T >
88 {
9- protected PyObject pyObject ;
9+ protected readonly PyObject pyObject ;
1010
1111 public IterableWrapper ( PyObject pyObj )
1212 {
13+ if ( pyObj == null )
14+ throw new PythonException ( ) ;
1315 pyObject = pyObj ;
1416 }
1517
1618 private void propagateIterationException ( )
1719 {
1820 var err = Runtime . PyErr_Occurred ( ) ;
19- if ( err != null && err != Exceptions . StopIteration )
21+ if ( err == null ) return ;
22+
23+ //remove StopIteration exceptions
24+ if ( 0 != Runtime . PyErr_ExceptionMatches ( Exceptions . StopIteration ) )
2025 {
21- Runtime . CheckExceptionOccurred ( ) ;
26+ Runtime . PyErr_Clear ( ) ;
27+ return ;
2228 }
29+
30+ Runtime . CheckExceptionOccurred ( ) ;
2331 }
2432
2533 IEnumerator IEnumerable . GetEnumerator ( )
2634 {
27- if ( pyObject == null ) yield break ;
28- PyObject iterObject = new PyObject ( Runtime . PyObject_GetIter ( pyObject . Handle ) ) ;
29- IntPtr item ;
35+ PyObject iterObject = null ;
36+ using ( Py . GIL ( ) )
37+ {
38+ iterObject = new PyObject ( Runtime . PyObject_GetIter ( pyObject . Handle ) ) ;
39+ }
3040
31- while ( ( item = Runtime . PyIter_Next ( iterObject . Handle ) ) != IntPtr . Zero )
41+ while ( true )
3242 {
43+ IntPtr item = IntPtr . Zero ;
44+ using ( Py . GIL ( ) )
45+ {
46+ item = Runtime . PyIter_Next ( iterObject . Handle ) ;
47+ }
48+ if ( item == IntPtr . Zero ) break ;
49+
3350 object obj = null ;
3451 if ( ! Converter . ToManaged ( item , typeof ( object ) , out obj , true ) )
3552 {
@@ -46,7 +63,6 @@ IEnumerator IEnumerable.GetEnumerator()
4663
4764 public IEnumerator < T > GetEnumerator ( )
4865 {
49- if ( pyObject == null ) yield break ;
5066 PyObject iterObject = null ;
5167 using ( Py . GIL ( ) )
5268 {
0 commit comments