summaryrefslogtreecommitdiff
path: root/django/utils/itercompat.py
diff options
context:
space:
mode:
authorMalcolm Tredinnick <malcolm.tredinnick@gmail.com>2006-09-26 06:33:32 +0000
committerMalcolm Tredinnick <malcolm.tredinnick@gmail.com>2006-09-26 06:33:32 +0000
commita27f12f3884de8c51b7f8bf6fd669d38f449360c (patch)
tree02d22a64dce76290bf2610b214f5a793554d9519 /django/utils/itercompat.py
parentbe053df69341e98ef46c6ec3429d8f0812aab9f0 (diff)
Fixed #2265 -- Fixed problem with using iterators for "choices" attribute.
Thanks, Alex Dedul. git-svn-id: http://code.djangoproject.com/svn/django/trunk@3851 bcc190cf-cafb-0310-a4f2-bffc1f526a37
Diffstat (limited to 'django/utils/itercompat.py')
-rw-r--r--django/utils/itercompat.py31
1 files changed, 31 insertions, 0 deletions
diff --git a/django/utils/itercompat.py b/django/utils/itercompat.py
new file mode 100644
index 0000000000..f259b26139
--- /dev/null
+++ b/django/utils/itercompat.py
@@ -0,0 +1,31 @@
+"""
+Providing iterator functions that are not in all version of Python we support.
+Where possible, we try to use the system-native version and only fall back to
+these implementations if necessary.
+"""
+
+import itertools
+
+def compat_tee(iterable):
+ """Return two independent iterators from a single iterable.
+
+ Based on http://www.python.org/doc/2.3.5/lib/itertools-example.html
+ """
+ # Note: Using a dictionary and a list as the default arguments here is
+ # deliberate and safe in this instance.
+ def gen(next, data={}, cnt=[0]):
+ dpop = data.pop
+ for i in count():
+ if i == cnt[0]:
+ item = data[i] = next()
+ cnt[0] += 1
+ else:
+ item = dpop(i)
+ yield item
+ next = iter(iterable).next
+ return gen(next), gen(next)
+
+if hasattr(itertools, 'tee'):
+ tee = itertools.tee
+else:
+ tee = compat_tee