Skip to content

Commit ad0d4e7

Browse files
committed
allow dynamic PyObject conversion to IEnumerable when the object is a Python iterable
this enables foreach loops over dynamic PyObject instances closes #1680
1 parent dd3302a commit ad0d4e7

File tree

2 files changed

+17
-0
lines changed

2 files changed

+17
-0
lines changed

src/embed_tests/dynamic.cs

+11
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
using System;
2+
using System.Collections.Generic;
23
using System.Text;
34
using NUnit.Framework;
45
using Python.Runtime;
@@ -126,5 +127,15 @@ public void PassPyObjectInNet()
126127
// Compare in .NET
127128
Assert.IsTrue(sys.testattr1.Equals(sys.testattr2));
128129
}
130+
131+
// regression test for https://github.com/pythonnet/pythonnet/issues/1680
132+
[Test]
133+
public void ForEach()
134+
{
135+
dynamic pyList = PythonEngine.Eval("[1,2,3]");
136+
var list = new List<int>();
137+
foreach (int item in pyList)
138+
list.Add(item);
139+
}
129140
}
130141
}

src/runtime/PythonTypes/PyObject.cs

+6
Original file line numberDiff line numberDiff line change
@@ -1296,6 +1296,12 @@ public override bool TryConvert(ConvertBinder binder, out object? result)
12961296
return converted;
12971297
}
12981298

1299+
if (binder.Type == typeof(System.Collections.IEnumerable) && this.IsIterable())
1300+
{
1301+
result = new PyIterable(this.Reference);
1302+
return true;
1303+
}
1304+
12991305
return false;
13001306
}
13011307

0 commit comments

Comments
 (0)