[ovs-dev] [python2] python: Use enumerate() builtin function to simplify counted iteration.

Ben Pfaff blp at nicira.com
Tue Aug 23 14:45:24 PDT 2011


Suggested-by: Reid Price <reid at nicira.com>
---
Here's another one that I missed before.

diff --git a/python/ovs/db/data.py b/python/ovs/db/data.py
index 90ad7dd..9cab2a4 100644
--- a/python/ovs/db/data.py
+++ b/python/ovs/db/data.py
@@ -348,11 +348,9 @@ class Datum(object):
         if head:
             s.append(head)
 
-        i = 0
-        for key in sorted(self.values):
+        for i, key in enumerate(sorted(self.values)):
             if i:
                 s.append(", ")
-            i += 1
 
             s.append(key.to_string())
             if self.type.is_map():
@@ -412,18 +410,14 @@ class Datum(object):
         s += ["%s->keys = xmalloc(%d * sizeof *%s->keys);"
               % (var, len(self.values), var)]
 
-        i = 0
-        for key, value in sorted(self.values.items()):
+        for i, key in enumerate(sorted(self.values)):
             s += key.cInitAtom("%s->keys[%d]" % (var, i))
-            i += 1
         
         if self.type.value:
             s += ["%s->values = xmalloc(%d * sizeof *%s->values);"
                   % (var, len(self.values), var)]
-            i = 0
-            for key, value in sorted(self.values.items()):
+            for i, (key, value) in enumerate(sorted(self.values.items())):
                 s += value.cInitAtom("%s->values[%d]" % (var, i))
-                i += 1
         else:
             s += ["%s->values = NULL;" % var]
 
diff --git a/python/ovs/json.py b/python/ovs/json.py
index 6362830..1668e46 100644
--- a/python/ovs/json.py
+++ b/python/ovs/json.py
@@ -51,22 +51,18 @@ def to_stream(obj, stream, pretty=False, sort_keys=True):
             items = sorted(obj.items())
         else:
             items = obj.iteritems()
-        i = 0
-        for key, value in items:
+        for i, (key, value) in enumerate(items):
             if i > 0:
                 stream.write(u",")
-            i += 1
             __dump_string(stream, unicode(key))
             stream.write(u":")
             to_stream(value, stream, pretty, sort_keys)
         stream.write(u"}")
     elif type(obj) in (list, tuple):
         stream.write(u"[")
-        i = 0
-        for value in obj:
+        for i, value in enumerate(obj):
             if i > 0:
                 stream.write(u",")
-            i += 1
             to_stream(value, stream, pretty, sort_keys)
         stream.write(u"]")
     else:
-- 
1.7.4.4




More information about the dev mailing list