[Jython-checkins] jython: add __builtin__.next

philip.jenvey jython-checkins at python.org
Mon Nov 7 02:55:55 CET 2011


http://hg.python.org/jython/rev/91b69979ac44
changeset:   6273:91b69979ac44
user:        Philip Jenvey <pjenvey at underboss.org>
date:        Sun Nov 06 17:54:18 2011 -0800
summary:
  add __builtin__.next

files:
  src/org/python/core/__builtin__.java |  32 ++++++++++++++++
  1 files changed, 32 insertions(+), 0 deletions(-)


diff --git a/src/org/python/core/__builtin__.java b/src/org/python/core/__builtin__.java
--- a/src/org/python/core/__builtin__.java
+++ b/src/org/python/core/__builtin__.java
@@ -361,6 +361,7 @@
         dict.__setitem__("any", new AnyFunction());
         dict.__setitem__("format", new FormatFunction());
         dict.__setitem__("print", new PrintFunction());
+        dict.__setitem__("next", new NextFunction());
     }
 
     public static PyObject abs(PyObject o) {
@@ -1662,3 +1663,34 @@
         return PyFile.TYPE.__call__(args, kwds);
     }
 }
+
+class NextFunction extends PyBuiltinFunction {
+    NextFunction() {
+        super("next", "next(iterator[, default])\n\n"
+              + "Return the next item from the iterator. If default is given and the iterator\n"
+              + "is exhausted, it is returned instead of raising StopIteration.");
+    }
+
+    @Override
+    public PyObject __call__(PyObject args[], String kwds[]) {
+        ArgParser ap = new ArgParser("next", args, kwds, new String[] {"iterator", "default"}, 1);
+        ap.noKeywords();
+        PyObject it = ap.getPyObject(0);
+        PyObject def = ap.getPyObject(1, null);
+
+        PyObject next;
+        if ((next = it.__findattr__("next")) == null) {
+            throw Py.TypeError(String.format("'%.200s' object is not an iterator",
+                                             it.getType().fastGetName()));
+        }
+
+        try {
+            return next.__call__();
+        } catch (PyException pye) {
+            if (!pye.match(Py.StopIteration) || def == null) {
+                throw pye;
+            }
+        }
+        return def;
+    }
+}

-- 
Repository URL: http://hg.python.org/jython


More information about the Jython-checkins mailing list