]> arthur.barton.de Git - bup.git/commitdiff
Only define helpers.next() if Python's isn't new enough.
authorRob Browning <rlb@defaultvalue.org>
Thu, 8 May 2014 16:50:29 +0000 (11:50 -0500)
committerRob Browning <rlb@defaultvalue.org>
Thu, 8 May 2014 17:47:12 +0000 (12:47 -0500)
Since helpers.next() now matches the Python built-in's semantics
(since Python 2.6), just rely on the built-in when it's new enough.
Otherwise, set up a matching replacement.

Borrow the fallback next documentation string from Python.

Signed-off-by: Rob Browning <rlb@defaultvalue.org>
lib/bup/helpers.py
lib/bup/t/thelpers.py

index 4943d70ccc6c748a157c871757848e99a478ac01..ef4be682f0152d26c372ca1a8078619a30a5ab49 100644 (file)
@@ -126,6 +126,25 @@ def mkdirp(d, mode=None):
             raise
 
 
+_unspecified_next_default = object()
+
+def _fallback_next(it, default=_unspecified_next_default):
+    """Retrieve the next item from the iterator by calling its
+    next() method. If default is given, it is returned if the
+    iterator is exhausted, otherwise StopIteration is raised."""
+
+    if default is _unspecified_next_default:
+        return it.next()
+    else:
+        try:
+            return it.next()
+        except StopIteration:
+            return default
+
+if sys.version_info < (2, 6):
+    next =  _fallback_next
+
+
 def merge_iter(iters, pfreq, pfunc, pfinal, key=None):
     if key:
         samekey = lambda e, pe: getattr(e, key) == getattr(pe, key, None)
index fd041ffb792e3586259581dd70719ccf7b4c867a..d260f8e767a57655796cd8e0c02efce306e89879 100644 (file)
@@ -1,9 +1,38 @@
+import helpers
 import math
 import os
 import bup._helpers as _helpers
 from bup.helpers import *
 from wvtest import *
 
+
+@wvtest
+def test_next():
+    # Test whatever you end up with for next() after import '*'.
+    WVPASSEQ(next(iter([]), None), None)
+    x = iter([1])
+    WVPASSEQ(next(x, None), 1)
+    WVPASSEQ(next(x, None), None)
+    x = iter([1])
+    WVPASSEQ(next(x, 'x'), 1)
+    WVPASSEQ(next(x, 'x'), 'x')
+    WVEXCEPT(StopIteration, next, iter([]))
+    x = iter([1])
+    WVPASSEQ(next(x), 1)
+    WVEXCEPT(StopIteration, next, x)
+
+
+@wvtest
+def test_fallback_next():
+    global next
+    orig = next
+    next = helpers._fallback_next
+    try:
+        test_next()
+    finally:
+        next = orig
+
+
 @wvtest
 def test_parse_num():
     pn = parse_num