Commits

Killian De Smedt committed 969db8d

Some more python2.x compatibility fixes

Comments (0)

Files changed (1)

protobuf/message.py

 from collections import namedtuple
 from functools import partial
 from struct import Struct
+from sys import version
+
+_array_to_bytes = lambda ar: ar.tostring() if version.startswith('2') else ar.tobytes()
 
 # We could probably speed things up a lot by encoding the tags
 # when creating the messages and always work with those
 
 def encode_varint(i):
-    result = array('B')
+    result = array(str('B'))
     while i > 0x7F:
         result.append((i & 0x7F) | 0x80)
         i >>= 7
     result.append(i & 0x7F)
-    return result.tobytes()
+    return _array_to_bytes(result)
 
 def decode_varint(encoded):
     result = 0
         return ''.join(result)
     
     def serialize_to_string(self):
-        result = array('B')
+        result = array(str('B'))
         for tag, field in self.__class__._fields.items():
             value = getattr(self, field.name, None)
             if isinstance(value, list):
             elif value is not None:
                 result.extend(tag)
                 result.extend(field.encode(value))
-        return result.tobytes()
+        return _array_to_bytes(result)
     
     def parse_from_string(self, bytestring):
         for tag, value in _decode_msg(bytestring):