[ovs-dev] [PATCH 17/55] python: Drop usage of long type.

Russell Bryant russell at ovn.org
Mon Dec 21 20:47:17 UTC 2015


Python 2 has both long and int types.  Python 3 only has int, which
behaves like long.

In the case of needing a set of integer types, we can use
six.integer_types which includes int and long for Python 2 and just int
for Python 3.

We can convert all cases of long(value) to int(value), because as of
Python 2.4, when the result of an operation would be too big for an int,
the type is automatically converted to a long.

There were several places in this patch doing type comparisons.  The
preferred way to do this is using the isinstance() or issubclass()
built-in functions, so I converted the similar checks nearby while I was
at it.

Signed-off-by: Russell Bryant <russell at ovn.org>
---
 python/ovs/db/data.py   | 20 ++++++++++++--------
 python/ovs/db/idl.py    |  4 ++--
 python/ovs/db/parser.py | 15 ++++++++++-----
 python/ovs/db/types.py  | 20 +++++++++++++-------
 python/ovs/json.py      | 21 ++++++++++++---------
 python/ovstest/args.py  |  2 +-
 python/ovstest/tests.py |  4 ++--
 7 files changed, 52 insertions(+), 34 deletions(-)

diff --git a/python/ovs/db/data.py b/python/ovs/db/data.py
index cd535d4..9cbf425 100644
--- a/python/ovs/db/data.py
+++ b/python/ovs/db/data.py
@@ -108,12 +108,16 @@ class Atom(object):
     def from_json(base, json, symtab=None):
         type_ = base.type
         json = ovs.db.parser.float_to_int(json)
-        if ((type_ == ovs.db.types.IntegerType and type(json) in [int, long])
+        real_types = list(six.integer_types)
+        real_types.extend([float])
+        real_types = tuple(real_types)
+        if ((type_ == ovs.db.types.IntegerType
+                and isinstance(json, six.integer_types))
             or (type_ == ovs.db.types.RealType
-                and type(json) in [int, long, float])
-            or (type_ == ovs.db.types.BooleanType and type(json) == bool)
+                and isinstance(json, real_types))
+            or (type_ == ovs.db.types.BooleanType and isinstance(json, bool))
             or (type_ == ovs.db.types.StringType
-                and type(json) in [str, unicode])):
+                and isinstance(json, (str, unicode)))):
             atom = Atom(type_, json)
         elif type_ == ovs.db.types.UuidType:
             atom = Atom(type_, ovs.ovsuuid.from_json(json, symtab))
@@ -237,13 +241,13 @@ class Atom(object):
 
     @staticmethod
     def new(x):
-        if type(x) in [int, long]:
+        if isinstance(x, six.integer_types):
             t = ovs.db.types.IntegerType
-        elif type(x) == float:
+        elif isinstance(x, float):
             t = ovs.db.types.RealType
-        elif x in [False, True]:
+        elif isinstance(x, bool):
             t = ovs.db.types.BooleanType
-        elif type(x) in [str, unicode]:
+        elif isinstance(x, (str, unicode)):
             t = ovs.db.types.StringType
         elif isinstance(x, uuid):
             t = ovs.db.types.UuidType
diff --git a/python/ovs/db/idl.py b/python/ovs/db/idl.py
index 02950d3..26cf6d7 100644
--- a/python/ovs/db/idl.py
+++ b/python/ovs/db/idl.py
@@ -1252,7 +1252,7 @@ class Transaction(object):
         # __process_reply() already checked.
         mutate = ops[self._inc_index]
         count = mutate.get("count")
-        if not Transaction.__check_json_type(count, (int, long),
+        if not Transaction.__check_json_type(count, six.integer_types,
                                              '"mutate" reply "count"'):
             return False
         if count != 1:
@@ -1275,7 +1275,7 @@ class Transaction(object):
                                              '"select" reply row'):
             return False
         column = row.get(self._inc_column)
-        if not Transaction.__check_json_type(column, (int, long),
+        if not Transaction.__check_json_type(column, six.integer_types,
                                              '"select" reply inc column'):
             return False
         self._inc_new_value = column
diff --git a/python/ovs/db/parser.py b/python/ovs/db/parser.py
index 81caedb..293dd98 100644
--- a/python/ovs/db/parser.py
+++ b/python/ovs/db/parser.py
@@ -14,6 +14,8 @@
 
 import re
 
+import six
+
 from ovs.db import error
 
 
@@ -80,17 +82,20 @@ def is_identifier(s):
 
 
 def json_type_to_string(type_):
+    number_types = list(six.integer_types)
+    number_types.extend([float])
+    number_types = tuple(number_types)
     if type_ is None:
         return "null"
-    elif type_ == bool:
+    elif issubclass(type_, bool):
         return "boolean"
-    elif type_ == dict:
+    elif issubclass(type_, dict):
         return "object"
-    elif type_ == list:
+    elif issubclass(type_, list):
         return "array"
-    elif type_ in [int, long, float]:
+    elif issubclass(type_, number_types):
         return "number"
-    elif type_ in [str, unicode]:
+    elif issubclass(type_, (str, unicode)):
         return "string"
     else:
         return "<invalid>"
diff --git a/python/ovs/db/types.py b/python/ovs/db/types.py
index c858471..d7ce00a 100644
--- a/python/ovs/db/types.py
+++ b/python/ovs/db/types.py
@@ -15,6 +15,8 @@
 import sys
 import uuid
 
+import six
+
 from ovs.db import error
 import ovs.db.parser
 import ovs.db.data
@@ -54,9 +56,13 @@ class AtomicType(object):
     def default_atom(self):
         return ovs.db.data.Atom(self, self.default)
 
+REAL_PYTHON_TYPES = list(six.integer_types)
+REAL_PYTHON_TYPES.extend([float])
+REAL_PYTHON_TYPES = tuple(REAL_PYTHON_TYPES)
+
 VoidType = AtomicType("void", None, ())
-IntegerType = AtomicType("integer", 0, (int, long))
-RealType = AtomicType("real", 0.0, (int, long, float))
+IntegerType = AtomicType("integer", 0, six.integer_types)
+RealType = AtomicType("real", 0.0, REAL_PYTHON_TYPES)
 BooleanType = AtomicType("boolean", False, (bool,))
 StringType = AtomicType("string", "", (str, unicode))
 UuidType = AtomicType("uuid", ovs.ovsuuid.zero(), (uuid.UUID,))
@@ -148,7 +154,7 @@ class BaseType(object):
 
     @staticmethod
     def __parse_uint(parser, name, default):
-        value = parser.get_optional(name, [int, long])
+        value = parser.get_optional(name, six.integer_types)
         if value is None:
             value = default
         else:
@@ -173,14 +179,14 @@ class BaseType(object):
             base.enum = ovs.db.data.Datum.from_json(
                     BaseType.get_enum_type(base.type), enum)
         elif base.type == IntegerType:
-            base.min = parser.get_optional("minInteger", [int, long])
-            base.max = parser.get_optional("maxInteger", [int, long])
+            base.min = parser.get_optional("minInteger", six.integer_types)
+            base.max = parser.get_optional("maxInteger", six.integer_types)
             if (base.min is not None and base.max is not None
                     and base.min > base.max):
                 raise error.Error("minInteger exceeds maxInteger", json)
         elif base.type == RealType:
-            base.min = parser.get_optional("minReal", [int, long, float])
-            base.max = parser.get_optional("maxReal", [int, long, float])
+            base.min = parser.get_optional("minReal", REAL_PYTHON_TYPES)
+            base.max = parser.get_optional("maxReal", REAL_PYTHON_TYPES)
             if (base.min is not None and base.max is not None
                     and base.min > base.max):
                 raise error.Error("minReal exceeds maxReal", json)
diff --git a/python/ovs/json.py b/python/ovs/json.py
index d5f9703..042f366 100644
--- a/python/ovs/json.py
+++ b/python/ovs/json.py
@@ -57,15 +57,15 @@ class _Serializer(object):
             self.stream.write(u"false")
         elif obj is True:
             self.stream.write(u"true")
-        elif type(obj) in (int, long):
+        elif isinstance(obj, six.integer_types):
             self.stream.write(u"%d" % obj)
-        elif type(obj) == float:
+        elif isinstance(obj, float):
             self.stream.write("%.15g" % obj)
-        elif type(obj) == unicode:
+        elif isinstance(obj, unicode):
             self.__serialize_string(obj)
-        elif type(obj) == str:
+        elif isinstance(obj, str):
             self.__serialize_string(unicode(obj))
-        elif type(obj) == dict:
+        elif isinstance(obj, dict):
             self.stream.write(u"{")
 
             self.depth += 1
@@ -87,7 +87,7 @@ class _Serializer(object):
 
             self.stream.write(u"}")
             self.depth -= 1
-        elif type(obj) in (list, tuple):
+        elif isinstance(obj, (list, tuple)):
             self.stream.write(u"[")
             self.depth += 1
 
@@ -248,7 +248,7 @@ class Parser(object):
         if m:
             sign, integer, fraction, exp = m.groups()
             if (exp is not None and
-                (long(exp) > sys.maxint or long(exp) < -sys.maxint - 1)):
+                (int(exp) > sys.maxint or int(exp) < -sys.maxint - 1)):
                 self.__error("exponent outside valid range")
                 return
 
@@ -264,7 +264,7 @@ class Parser(object):
             if fraction is not None:
                 pow10 -= len(fraction)
             if exp is not None:
-                pow10 += long(exp)
+                pow10 += int(exp)
 
             if significand == 0:
                 self.__parser_input(0)
@@ -527,7 +527,10 @@ class Parser(object):
                 self.parse_state = Parser.__parse_object_next
 
     def __parse_value(self, token, string, next_state):
-        if token in [False, None, True] or type(token) in [int, long, float]:
+        number_types = list(six.integer_types)
+        number_types.extend([float])
+        number_types = tuple(number_types)
+        if token in [False, None, True] or isinstance(token, number_types):
             self.__put_value(token)
         elif token == 'string':
             self.__put_value(string)
diff --git a/python/ovstest/args.py b/python/ovstest/args.py
index 4344979..975d188 100644
--- a/python/ovstest/args.py
+++ b/python/ovstest/args.py
@@ -161,7 +161,7 @@ def bandwidth(string):
         raise argparse.ArgumentTypeError("Not a valid target bandwidth")
     bwidth = string.replace("M", "000000")
     bwidth = bwidth.replace("K", "000")
-    return long(bwidth) / 8  # Convert from bits to bytes
+    return int(bwidth) / 8  # Convert from bits to bytes
 
 
 def tunnel_types(string):
diff --git a/python/ovstest/tests.py b/python/ovstest/tests.py
index 748607f..db3401f 100644
--- a/python/ovstest/tests.py
+++ b/python/ovstest/tests.py
@@ -96,8 +96,8 @@ def do_tcp_tests(receiver, sender, duration):
 
         time.sleep(duration + 1)
 
-        rcv_bytes = long(server1.get_tcp_listener_results(listen_handle))
-        snt_bytes = long(server2.get_tcp_sender_results(send_handle))
+        rcv_bytes = int(server1.get_tcp_listener_results(listen_handle))
+        snt_bytes = int(server2.get_tcp_sender_results(send_handle))
 
         bwidth = rcv_bytes / duration
 
-- 
2.5.0




More information about the dev mailing list