From 19aee08a6e8e22ad186ee787adc34a5076a6f272 Mon Sep 17 00:00:00 2001 From: Victor Nova Date: Thu, 17 Feb 2022 10:17:56 -0800 Subject: [PATCH] allow dynamic PyObject conversion to IEnumerable when the object is a Python iterable this enables foreach loops over dynamic PyObject instances closes https://github.com/pythonnet/pythonnet/issues/1680 --- src/embed_tests/dynamic.cs | 11 +++++++++++ src/runtime/PythonTypes/PyObject.cs | 6 ++++++ 2 files changed, 17 insertions(+) diff --git a/src/embed_tests/dynamic.cs b/src/embed_tests/dynamic.cs index 827782a5c..0a181231c 100644 --- a/src/embed_tests/dynamic.cs +++ b/src/embed_tests/dynamic.cs @@ -1,4 +1,5 @@ using System; +using System.Collections.Generic; using System.Text; using NUnit.Framework; using Python.Runtime; @@ -126,5 +127,15 @@ public void PassPyObjectInNet() // Compare in .NET Assert.IsTrue(sys.testattr1.Equals(sys.testattr2)); } + + // regression test for https://github.com/pythonnet/pythonnet/issues/1680 + [Test] + public void ForEach() + { + dynamic pyList = PythonEngine.Eval("[1,2,3]"); + var list = new List(); + foreach (int item in pyList) + list.Add(item); + } } } diff --git a/src/runtime/PythonTypes/PyObject.cs b/src/runtime/PythonTypes/PyObject.cs index 373751cf6..e26831490 100644 --- a/src/runtime/PythonTypes/PyObject.cs +++ b/src/runtime/PythonTypes/PyObject.cs @@ -1296,6 +1296,12 @@ public override bool TryConvert(ConvertBinder binder, out object? result) return converted; } + if (binder.Type == typeof(System.Collections.IEnumerable) && this.IsIterable()) + { + result = new PyIterable(this.Reference); + return true; + } + return false; } pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy