From a5037ad24f67bdaadb5dda08c5fc5d5c5dbd0b22 Mon Sep 17 00:00:00 2001
From: Karl-Hermann Wieners <karl-hermann.wieners@mpimet.mpg.de>
Date: Tue, 6 Dec 2022 15:50:57 +0100
Subject: [PATCH] Templates: allow use of iterators with 'list' and 'join'
 filters

---
 CHANGES.txt |  5 +++++
 mkexp       |  5 +++--
 test.py     | 14 ++++++++++++++
 3 files changed, 22 insertions(+), 2 deletions(-)

diff --git a/CHANGES.txt b/CHANGES.txt
index b40c3c4..c334719 100644
--- a/CHANGES.txt
+++ b/CHANGES.txt
@@ -14,6 +14,11 @@ Config
 
 * Added shared namelist settings ([[namelist_a, namelist_b]])
 
+Templates
+---------
+
+* Allow use of iterators with 'list' and 'join' filters
+
 Release 1.2.0
 =============
 
diff --git a/mkexp b/mkexp
index 5ed63f4..84cdb07 100755
--- a/mkexp
+++ b/mkexp
@@ -7,6 +7,7 @@
 
 from __future__ import print_function
 
+from collections.abc import Iterator
 import io
 import os
 import re
@@ -358,7 +359,7 @@ def list_singleton(eval_ctx, x, keep_empty=False, *args, **kwargs):
     # Workaround for 2.8 bug when applied to literals
     if isinstance(x, jinja2.nodes.EvalContext):
         (eval_ctx, x) = (x, eval_ctx)
-    if isinstance(x, (list, tuple)):
+    if isinstance(x, (list, tuple, Iterator)):
         if getattr(list_original, 'evalcontextfilter', getattr(list_original, 'jinja_pass_arg', False)):
             return list_original(eval_ctx, x, *args, **kwargs)
         return list_original(x, *args, **kwargs)
@@ -374,7 +375,7 @@ def join_singleton(eval_ctx, x, *args, **kwargs):
     # Workaround for 2.8 bug when applied to literals
     if isinstance(x, jinja2.nodes.EvalContext):
         (eval_ctx, x) = (x, eval_ctx)
-    if isinstance(x, (list, tuple)):
+    if isinstance(x, (list, tuple, Iterator)):
         return join_original(eval_ctx, x, *args, **kwargs)
     return x
 template_env.filters['join'] = join_singleton
diff --git a/test.py b/test.py
index f490fc1..0a1be0a 100644
--- a/test.py
+++ b/test.py
@@ -1118,6 +1118,13 @@ class ListTestCase(MkexpSimpleTestCase):
              ['first', 'second', 'third']
         """)
 
+    def test_list_on_iterator(self):
+        self.run_test(u"""
+            %{('first', 'second', 'third')|reverse|list}
+        """, u"""
+             ['third', 'second', 'first']
+        """)
+
 class JoinTestCase(MkexpSimpleTestCase):
 
     def test_join_on_string(self):
@@ -1154,6 +1161,13 @@ class JoinTestCase(MkexpSimpleTestCase):
              first, second, third
         """)
 
+    def test_join_on_iterator(self):
+        self.run_test(u"""
+            %{('first', 'second', 'third')|reverse|join(', ')}
+        """, u"""
+             third, second, first
+        """)
+
 class IsSetTestCase(MkexpSimpleTestCase):
 
     def test_empty_string(self):
-- 
GitLab