Kenton Varda wrote:
> Does Python 3.x implement metaclasses the same way?  It looks to me like
> the metaclass may not be getting applied.

AIUI, setuptools (and therefore pkg_resources) have not yet been ported
to python3 yet. I believe there are discussions about including
pkg_resources directly in python3 (perhaps via distutils), but the PEP
seems withdrawn.


Python 2.6.2 (release26-maint, Apr 19 2009, 01:58:18)
[GCC 4.3.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> __import__('pkg_resources').declare_namespace(__name__)
>>>
mord...@camelot:~/src/protobuf/protobuf/python/google$ python3
Python 3.0.1+ (r301:69556, Apr 15 2009, 17:25:52)
[GCC 4.3.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> __import__('pkg_resources').declare_namespace(__name__)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ImportError: No module named pkg_resources

However, there is this:

from pkgutil import extend_path
__path__ = extend_path(__path__, __name__)

That can be used to do namespace packages in python3.

You're going to run in to more problems than just that, of course. I'm
supposing you're already looking at 2to3? buffer() needs to turn in to
memoryview() - for one.

...

Ok. I got it to work.

There will need to be changes to the python emitted by protoc.
(specifically the metaclass stuff Kenton was mentioning) That should
look like this:

class Schema(message.Message, metaclass =
reflection.GeneratedProtocolMessageType):

Also, default_value="" instead of default_value=unicode("", "utf-8")

I'm attaching a schema.proto and the edited/generated code.

I've also got a diff (attaching) to the python dir that works with
python3. I have not patched protoc, nor have I done significant testing,
but this works:

mord...@camelot:~/src/drizzle/mordred/drizzled/message$ python3
Python 3.0.1+ (r301:69556, Apr 15 2009, 17:25:52)
[GCC 4.3.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import schema_pb2
>>> s=schema_pb2.Schema()
>>> s.name="foo"
>>> print(s.SerializeToString())
b'\n\x03foo'

Hope this helps. (Sorry for the rambling brain-dump)

Monty


> On Mon, Sep 14, 2009 at 5:21 PM, cjimison <cjimi...@gmail.com
> <mailto:cjimi...@gmail.com>> wrote:
> 
> 
>     Hi all,
> 
>     Our application has an embedded python 3.1 interpreter and we would
>     really like to use protocol buffers.  I have started to make the
>     protocol buffers python 3 compatible but I am running into issues with
>     starting up the module.  I create a very simple proto definition in a
>     file Example.proto:
> 
>     package tutorial;
> 
>     message MyTest {
>        required string name = 1;
>     }
> 
>     and generated the Example_pb2.proto file with no problems at all.
>     When I run the following script:
> 
>     import Example_pb2
> 
>     test = Example_pb2.MyTest()
>     test.name <http://test.name> = "Bob"
>     test.SerializeToString()    # ERROR raise NotImplementedError
>     NotImplementedError
> 
>     It looks to me like it is trying to call the SerializeToString in the
>     message.py message class which should be abstract.  I had to remove
>     the __import__('pkg_resources').declare_namespace(__name__) call in
>     python\google\__init__.py  so I think something is not getting
>     "initialized" correctly.
> 
>     Any ideas?
> 
>     Thanks for the help!
> 
> 
> 
> > 


--~--~---------~--~----~------------~-------~--~----~
You received this message because you are subscribed to the Google Groups 
"Protocol Buffers" group.
To post to this group, send email to protobuf@googlegroups.com
To unsubscribe from this group, send email to 
protobuf+unsubscr...@googlegroups.com
For more options, visit this group at 
http://groups.google.com/group/protobuf?hl=en
-~----------~----~----~----~------~----~------~--~---

# Generated by the protocol buffer compiler.  DO NOT EDIT!

from google.protobuf import descriptor
from google.protobuf import message
from google.protobuf import reflection
from google.protobuf import service
from google.protobuf import service_reflection
from google.protobuf import descriptor_pb2



_SCHEMA = descriptor.Descriptor(
  name='Schema',
  full_name='drizzled.message.Schema',
  filename='schema.proto',
  containing_type=None,
  fields=[
    descriptor.FieldDescriptor(
      name='name', full_name='drizzled.message.Schema.name', index=0,
      number=1, type=9, cpp_type=9, label=2,
      default_value="",
      message_type=None, enum_type=None, containing_type=None,
      is_extension=False, extension_scope=None,
      options=None),
    descriptor.FieldDescriptor(
      name='collation', full_name='drizzled.message.Schema.collation', index=1,
      number=2, type=9, cpp_type=9, label=1,
      default_value="",
      message_type=None, enum_type=None, containing_type=None,
      is_extension=False, extension_scope=None,
      options=None),
  ],
  extensions=[
  ],
  nested_types=[],  # TODO(robinson): Implement.
  enum_types=[
  ],
  options=None)



class Schema(message.Message, metaclass = reflection.GeneratedProtocolMessageType):
  DESCRIPTOR = _SCHEMA

package drizzled.message;
option optimize_for = SPEED;

message Schema {
  required string name = 1;
  optional string collation = 2;
}
=== modified file 'python/google/__init__.py'
--- python/google/__init__.py	2008-07-10 02:12:20 +0000
+++ python/google/__init__.py	2009-09-15 03:29:38 +0000
@@ -1,1 +1,2 @@
-__import__('pkg_resources').declare_namespace(__name__)
+from pkgutil import extend_path
+__path__ = extend_path(__path__, __name__)

=== modified file 'python/google/protobuf/internal/decoder.py'
--- python/google/protobuf/internal/decoder.py	2009-07-29 01:13:20 +0000
+++ python/google/protobuf/internal/decoder.py	2009-09-15 03:54:23 +0000
@@ -154,7 +154,7 @@
   def ReadString(self):
     """Reads and returns a length-delimited string."""
     bytes = self.ReadBytes()
-    return unicode(bytes, 'utf-8')
+    return bytes.decode('utf-8')
 
   def ReadBytes(self):
     """Reads and returns a length-delimited byte sequence."""

=== modified file 'python/google/protobuf/internal/decoder_test.py'
--- python/google/protobuf/internal/decoder_test.py	2009-07-29 01:13:20 +0000
+++ python/google/protobuf/internal/decoder_test.py	2009-09-15 03:54:49 +0000
@@ -125,9 +125,9 @@
          'ReadLittleEndian32', 0xffffffff],
         ['fixed64', decoder.Decoder.ReadFixed64, 0xffffffffffffffff,
         'ReadLittleEndian64', 0xffffffffffffffff],
-        ['sfixed32', decoder.Decoder.ReadSFixed32, long(-1),
-         'ReadLittleEndian32', long(0xffffffff)],
-        ['sfixed64', decoder.Decoder.ReadSFixed64, long(-1),
+        ['sfixed32', decoder.Decoder.ReadSFixed32, int(-1),
+         'ReadLittleEndian32', int(0xffffffff)],
+        ['sfixed64', decoder.Decoder.ReadSFixed64, int(-1),
          'ReadLittleEndian64', 0xffffffffffffffff],
         ['float', decoder.Decoder.ReadFloat, self.VAL,
          'ReadBytes', self.LITTLE_FLOAT_VAL, 4],
@@ -136,10 +136,10 @@
         ['bool', decoder.Decoder.ReadBool, True, 'ReadVarUInt32', 1],
         ['enum', decoder.Decoder.ReadEnum, 23, 'ReadVarUInt32', 23],
         ['string', decoder.Decoder.ReadString,
-         unicode(test_string, 'utf-8'), 'ReadBytes', test_string,
+         test_string, 'ReadBytes', test_string,
          len(test_string)],
         ['utf8-string', decoder.Decoder.ReadString,
-         unicode(test_string, 'utf-8'), 'ReadBytes', test_string,
+         test_string, 'ReadBytes', test_string,
          len(test_string)],
         ['bytes', decoder.Decoder.ReadBytes,
          test_string, 'ReadBytes', test_string, len(test_string)],

=== modified file 'python/google/protobuf/internal/encoder_test.py'
--- python/google/protobuf/internal/encoder_test.py	2009-07-29 01:13:20 +0000
+++ python/google/protobuf/internal/encoder_test.py	2009-09-15 03:53:30 +0000
@@ -124,12 +124,12 @@
     self.mox.ResetAll()
 
   VAL = 1.125  # Perfectly representable as a float (no rounding error).
-  LITTLE_FLOAT_VAL = '\x00\x00\x90?'
-  LITTLE_DOUBLE_VAL = '\x00\x00\x00\x00\x00\x00\xf2?'
+  LITTLE_FLOAT_VAL = b'\x00\x00\x90?'
+  LITTLE_DOUBLE_VAL = b'\x00\x00\x00\x00\x00\x00\xf2?'
 
   def testAppendScalars(self):
-    utf8_bytes = '\xd0\xa2\xd0\xb5\xd1\x81\xd1\x82'
-    utf8_string = unicode(utf8_bytes, 'utf-8')
+    utf8_bytes = b'\xd0\xa2\xd0\xb5\xd1\x81\xd1\x82'
+    utf8_string = utf8_bytes.decode('utf-8')
     scalar_tests = [
         ['int32', self.encoder.AppendInt32, 'AppendVarint32',
          wire_format.WIRETYPE_VARINT, 0],

=== modified file 'python/google/protobuf/internal/input_stream.py'
--- python/google/protobuf/internal/input_stream.py	2009-04-25 02:53:47 +0000
+++ python/google/protobuf/internal/input_stream.py	2009-09-15 03:37:02 +0000
@@ -151,7 +151,7 @@
                         self._buffer[self._pos : self._pos + 4])
       self._pos += 4
       return i[0]  # unpack() result is a 1-element tuple.
-    except struct.error, e:
+    except struct.error as e:
       raise message.DecodeError(e)
 
   def ReadLittleEndian64(self):
@@ -163,7 +163,7 @@
                         self._buffer[self._pos : self._pos + 8])
       self._pos += 8
       return i[0]  # unpack() result is a 1-element tuple.
-    except struct.error, e:
+    except struct.error as e:
       raise message.DecodeError(e)
 
   def ReadVarint32(self):
@@ -274,7 +274,7 @@
                         self._buffer[self._pos : self._pos + 4])
       self._pos += 4
       return i[0]  # unpack() result is a 1-element tuple.
-    except struct.error, e:
+    except struct.error as e:
       raise message.DecodeError(e)
 
   def ReadLittleEndian64(self):
@@ -283,7 +283,7 @@
                         self._buffer[self._pos : self._pos + 8])
       self._pos += 8
       return i[0]  # unpack() result is a 1-element tuple.
-    except struct.error, e:
+    except struct.error as e:
       raise message.DecodeError(e)
 
   def ReadVarint32(self):
@@ -336,3 +336,7 @@
 except RuntimeError:
   # Google App Engine: production
   InputStream = InputStreamArray
+except NameError:
+  # Python3:
+  # @TODO(Monty) Need to figure out how to do memoryview instead of buffer
+  InputStream = InputStreamArray

=== modified file 'python/google/protobuf/internal/output_stream_test.py'
--- python/google/protobuf/internal/output_stream_test.py	2008-11-21 00:06:27 +0000
+++ python/google/protobuf/internal/output_stream_test.py	2009-09-15 03:28:26 +0000
@@ -68,7 +68,7 @@
         long value as input.
       values_and_strings: Iterable of (value, expected_string) pairs.
     """
-    for conversion in (int, long):
+    for conversion in (int, int):
       for value, string in values_and_strings:
         stream = output_stream.OutputStream()
         expected_string = ''

=== modified file 'python/google/protobuf/internal/reflection_test.py'
--- python/google/protobuf/internal/reflection_test.py	2009-07-29 01:13:20 +0000
+++ python/google/protobuf/internal/reflection_test.py	2009-09-15 03:47:06 +0000
@@ -232,7 +232,7 @@
     proto.repeated_string.extend(['foo', 'bar'])
     proto.repeated_string.extend([])
     proto.repeated_string.append('baz')
-    proto.repeated_string.extend(str(x) for x in xrange(2))
+    proto.repeated_string.extend(str(x) for x in range(2))
     proto.optional_int32 = 21
     self.assertEqual(
       [ (proto.DESCRIPTOR.fields_by_name['optional_int32'  ], 21),
@@ -320,7 +320,7 @@
                      proto.default_import_enum)
 
     proto = unittest_pb2.TestExtremeDefaultValues()
-    self.assertEqual(u'\u1234', proto.utf8_string)
+    self.assertEqual('\u1234', proto.utf8_string)
 
   def testHasFieldWithUnknownFieldName(self):
     proto = unittest_pb2.TestAllTypes()
@@ -449,7 +449,7 @@
     self.assertEqual([5, 25, 20, 15, 30], proto.repeated_int32[:])
 
     # Test slice assignment with an iterator
-    proto.repeated_int32[1:4] = (i for i in xrange(3))
+    proto.repeated_int32[1:4] = (i for i in range(3))
     self.assertEqual([5, 0, 1, 2, 30], proto.repeated_int32)
 
     # Test slice assignment.
@@ -571,9 +571,8 @@
         containing_type=None, nested_types=[], enum_types=[],
         fields=[foo_field_descriptor], extensions=[],
         options=descriptor_pb2.MessageOptions())
-    class MyProtoClass(message.Message):
+    class MyProtoClass(message.Message, metaclass=reflection.GeneratedProtocolMessageType):
       DESCRIPTOR = mydescriptor
-      __metaclass__ = reflection.GeneratedProtocolMessageType
     myproto_instance = MyProtoClass()
     self.assertEqual(0, myproto_instance.foo_field)
     self.assertTrue(not myproto_instance.HasField('foo_field'))
@@ -1014,17 +1013,17 @@
 
     # Assignment of a unicode object to a field of type 'bytes' is not allowed.
     self.assertRaises(TypeError,
-                      setattr, proto, 'optional_bytes', u'unicode object')
+                      setattr, proto, 'optional_bytes', 'unicode object')
 
     # Check that the default value is of python's 'unicode' type.
-    self.assertEqual(type(proto.optional_string), unicode)
+    self.assertEqual(type(proto.optional_string), str)
 
-    proto.optional_string = unicode('Testing')
+    proto.optional_string = str('Testing')
     self.assertEqual(proto.optional_string, str('Testing'))
 
     # Assign a value of type 'str' which can be encoded in UTF-8.
     proto.optional_string = str('Testing')
-    self.assertEqual(proto.optional_string, unicode('Testing'))
+    self.assertEqual(proto.optional_string, str('Testing'))
 
     # Values of type 'str' are also accepted as long as they can be encoded in
     # UTF-8.
@@ -1044,7 +1043,7 @@
     extension_message = unittest_mset_pb2.TestMessageSetExtension2
     extension = extension_message.message_set_extension
 
-    test_utf8 = u'Тест'
+    test_utf8 = 'Тест'
     test_utf8_bytes = test_utf8.encode('utf-8')
 
     # 'Test' in another language, using UTF-8 charset.
@@ -1071,7 +1070,7 @@
         raw.item[0].message.endswith(test_utf8_bytes))
     message2.MergeFromString(raw.item[0].message)
 
-    self.assertEqual(type(message2.str), unicode)
+    self.assertEqual(type(message2.str), str)
     self.assertEqual(message2.str, test_utf8)
 
     # How about if the bytes on the wire aren't a valid UTF-8 encoded string.
@@ -1251,7 +1250,7 @@
       self.assertEqual(expected_varint_size + 1, self.Size())
     Test(0, 1)
     Test(1, 1)
-    for i, num_bytes in zip(range(7, 63, 7), range(1, 10000)):
+    for i, num_bytes in zip(list(range(7, 63, 7)), list(range(1, 10000))):
       Test((1 << i) - 1, num_bytes)
     Test(-1, 10)
     Test(-2, 10)
@@ -1697,7 +1696,7 @@
     """This method checks if the excpetion type and message are as expected."""
     try:
       callable_obj()
-    except exc_class, ex:
+    except exc_class as ex:
       # Check if the exception message is the right one.
       self.assertEqual(exception, str(ex))
       return

=== modified file 'python/google/protobuf/internal/text_format_test.py'
--- python/google/protobuf/internal/text_format_test.py	2009-07-29 01:13:20 +0000
+++ python/google/protobuf/internal/text_format_test.py	2009-09-15 03:47:16 +0000
@@ -257,7 +257,7 @@
 
     try:
       func(*args, **kwargs)
-    except e_class, expr:
+    except e_class as expr:
       if str(expr) != e:
         msg = '%s raised, but with wrong message: "%s" instead of "%s"'
         raise self.failureException(msg % (exc_name,

=== modified file 'python/google/protobuf/internal/type_checkers.py'
--- python/google/protobuf/internal/type_checkers.py	2009-07-29 01:13:20 +0000
+++ python/google/protobuf/internal/type_checkers.py	2009-09-15 04:01:02 +0000
@@ -98,9 +98,9 @@
   """Checker used for integer fields.  Performs type-check and range check."""
 
   def CheckValue(self, proposed_value):
-    if not isinstance(proposed_value, (int, long)):
+    if not isinstance(proposed_value, int):
       message = ('%.1024r has type %s, but expected one of: %s' %
-                 (proposed_value, type(proposed_value), (int, long)))
+                 (proposed_value, type(proposed_value), (int, int)))
       raise TypeError(message)
     if not self._MIN <= proposed_value <= self._MAX:
       raise ValueError('Value out of range: %d' % proposed_value)
@@ -111,17 +111,17 @@
   """Checker used for string fields."""
 
   def CheckValue(self, proposed_value):
-    if not isinstance(proposed_value, (str, unicode)):
+    if not isinstance(proposed_value, str):
       message = ('%.1024r has type %s, but expected one of: %s' %
-                 (proposed_value, type(proposed_value), (str, unicode)))
+                 (proposed_value, type(proposed_value), (str, str)))
       raise TypeError(message)
 
     # If the value is of type 'str' make sure that it is in 7-bit ASCII
     # encoding.
     if isinstance(proposed_value, str):
       try:
-        unicode(proposed_value, 'ascii')
-      except UnicodeDecodeError:
+        proposed_value.encode('ascii')
+      except UnicodeEncodeError:
         raise ValueError('%.1024r has type str, but isn\'t in 7-bit ASCII '
                          'encoding. Non-ASCII strings must be converted to '
                          'unicode objects before being added.' %
@@ -157,9 +157,9 @@
     _FieldDescriptor.CPPTYPE_UINT32: Uint32ValueChecker(),
     _FieldDescriptor.CPPTYPE_UINT64: Uint64ValueChecker(),
     _FieldDescriptor.CPPTYPE_DOUBLE: TypeChecker(
-        float, int, long),
+        float, int, int),
     _FieldDescriptor.CPPTYPE_FLOAT: TypeChecker(
-        float, int, long),
+        float, int, int),
     _FieldDescriptor.CPPTYPE_BOOL: TypeChecker(bool, int),
     _FieldDescriptor.CPPTYPE_ENUM: Int32ValueChecker(),
     _FieldDescriptor.CPPTYPE_STRING: TypeChecker(str),

=== modified file 'python/google/protobuf/internal/wire_format_test.py'
--- python/google/protobuf/internal/wire_format_test.py	2008-11-21 00:06:27 +0000
+++ python/google/protobuf/internal/wire_format_test.py	2009-09-15 03:52:10 +0000
@@ -195,7 +195,7 @@
     # Test UTF-8 string byte size calculation.
     # 1 byte for tag, 1 byte for length, 8 bytes for content.
     self.assertEqual(10, wire_format.StringByteSize(
-        5, unicode('\xd0\xa2\xd0\xb5\xd1\x81\xd1\x82', 'utf-8')))
+        5, b'\xd0\xa2\xd0\xb5\xd1\x81\xd1\x82'.decode('utf-8')))
 
     class MockMessage(object):
       def __init__(self, byte_size):

=== modified file 'python/google/protobuf/reflection.py'
--- python/google/protobuf/reflection.py	2009-07-29 01:13:20 +0000
+++ python/google/protobuf/reflection.py	2009-09-15 03:28:22 +0000
@@ -232,7 +232,7 @@
 
 def _AddClassAttributesForNestedExtensions(descriptor, dictionary):
   extension_dict = descriptor.extensions_by_name
-  for extension_name, extension_field in extension_dict.iteritems():
+  for extension_name, extension_field in extension_dict.items():
     assert extension_name not in dictionary
     dictionary[extension_name] = extension_field
 
@@ -307,7 +307,7 @@
       if field.label != _FieldDescriptor.LABEL_REPEATED:
         setattr(self, _HasFieldName(field.name), False)
     self.Extensions = _ExtensionDict(self, cls._known_extensions)
-    for field_name, field_value in kwargs.iteritems():
+    for field_name, field_value in kwargs.items():
       field = _GetFieldByName(message_descriptor, field_name)
       _MergeFieldOrExtension(self, field, field_value)
 
@@ -481,7 +481,7 @@
 def _AddPropertiesForExtensions(descriptor, cls):
   """Adds properties for all fields in this protocol message type."""
   extension_dict = descriptor.extensions_by_name
-  for extension_name, extension_field in extension_dict.iteritems():
+  for extension_name, extension_field in extension_dict.items():
     constant_name = extension_name.upper() + "_FIELD_NUMBER"
     setattr(cls, constant_name, extension_field.number)
 
@@ -510,7 +510,7 @@
   fields = sorted(message_descriptor.fields, key=lambda f: f.number)
   has_field_names = (_HasFieldName(f.name) for f in fields)
   value_field_names = (_ValueFieldName(f.name) for f in fields)
-  triplets = zip(has_field_names, value_field_names, fields)
+  triplets = list(zip(has_field_names, value_field_names, fields))
 
   def ListFields(self):
     # We need to list all extension and non-extension fields
@@ -743,7 +743,7 @@
 
   fields = message_descriptor.fields
   has_field_names = (_HasFieldName(f.name) for f in fields)
-  zipped = zip(has_field_names, fields)
+  zipped = list(zip(has_field_names, fields))
 
   def ByteSize(self):
     if not self._cached_byte_size_dirty:
@@ -822,7 +822,7 @@
   heap = []
   for index, it in enumerate(iters):
     try:
-      heap.append((it.next(), index))
+      heap.append((next(it), index))
     except StopIteration:
       pass
   heapq.heapify(heap)
@@ -831,7 +831,7 @@
     smallest_value, idx = heap[0]
     yield smallest_value
     try:
-      next_element = iters[idx].next()
+      next_element = next(iters[idx])
       heapq.heapreplace(heap, (next_element, idx))
     except StopIteration:
       heapq.heappop(heap)
@@ -1456,15 +1456,15 @@
     self._values = {}
     # Maps from extension handle ID to a boolean "has" bit, but only
     # for non-repeated extension fields.
-    keys = (id for id, extension in self._known_extensions.iteritems()
+    keys = (id for id, extension in self._known_extensions.items()
             if extension.label != _FieldDescriptor.LABEL_REPEATED)
     self._has_bits = dict.fromkeys(keys, False)
 
     self._extensions_by_number = dict(
-        (f.number, f) for f in self._known_extensions.itervalues())
+        (f.number, f) for f in self._known_extensions.values())
 
     self._extensions_by_name = {}
-    for extension in self._known_extensions.itervalues():
+    for extension in self._known_extensions.values():
       if (extension.containing_type.GetOptions().message_set_wire_format and
           extension.type == descriptor_mod.FieldDescriptor.TYPE_MESSAGE and
           extension.message_type == extension.extension_scope and
@@ -1501,7 +1501,7 @@
         if self._has_bits != other._has_bits:
           return False
         # If there's a "has" bit, then only compare values where it is true.
-        for k, v in self._values.iteritems():
+        for k, v in self._values.items():
           if self._has_bits.get(k, False) and v != other._values[k]:
             return False
         return True
@@ -1632,7 +1632,7 @@
     self._lock.acquire()  # Read-only methods must lock around self._values.
     try:
       set_extensions = []
-      for handle_id, value in self._values.iteritems():
+      for handle_id, value in self._values.items():
         handle = self._known_extensions[handle_id]
         if (handle.label == _FieldDescriptor.LABEL_REPEATED
             or self._has_bits[handle_id]):

=== modified file 'python/google/protobuf/text_format.py'
--- python/google/protobuf/text_format.py	2009-07-29 01:13:20 +0000
+++ python/google/protobuf/text_format.py	2009-09-15 03:53:05 +0000
@@ -32,7 +32,7 @@
 
 __author__ = 'ken...@google.com (Kenton Varda)'
 
-import cStringIO
+import io
 import re
 
 from collections import deque
@@ -48,7 +48,7 @@
 
 
 def MessageToString(message):
-  out = cStringIO.StringIO()
+  out = io.StringIO()
   PrintMessage(message, out)
   result = out.getvalue()
   out.close()
@@ -407,7 +407,7 @@
     """
     try:
       result = self._ParseInteger(self.token, is_signed=True, is_long=False)
-    except ValueError, e:
+    except ValueError as e:
       raise self._IntegerParseError(e)
     self.NextToken()
     return result
@@ -423,7 +423,7 @@
     """
     try:
       result = self._ParseInteger(self.token, is_signed=False, is_long=False)
-    except ValueError, e:
+    except ValueError as e:
       raise self._IntegerParseError(e)
     self.NextToken()
     return result
@@ -439,7 +439,7 @@
     """
     try:
       result = self._ParseInteger(self.token, is_signed=True, is_long=True)
-    except ValueError, e:
+    except ValueError as e:
       raise self._IntegerParseError(e)
     self.NextToken()
     return result
@@ -455,7 +455,7 @@
     """
     try:
       result = self._ParseInteger(self.token, is_signed=False, is_long=True)
-    except ValueError, e:
+    except ValueError as e:
       raise self._IntegerParseError(e)
     self.NextToken()
     return result
@@ -482,7 +482,7 @@
 
     try:
       result = float(text)
-    except ValueError, e:
+    except ValueError as e:
       raise self._FloatParseError(e)
     self.NextToken()
     return result
@@ -514,7 +514,7 @@
     Raises:
       ParseError: If a string value couldn't be consumed.
     """
-    return unicode(self.ConsumeByteString(), 'utf-8')
+    return self.ConsumeByteString().decode('utf-8')
 
   def ConsumeByteString(self):
     """Consumes a byte array value.
@@ -534,7 +534,7 @@
 
     try:
       result = _CUnescape(text[1:-1])
-    except ValueError, e:
+    except ValueError as e:
       raise self._ParseError(str(e))
     self.NextToken()
     return result

=== modified file 'python/setup.py'
--- python/setup.py	2009-08-13 22:41:37 +0000
+++ python/setup.py	2009-09-15 03:34:24 +0000
@@ -2,12 +2,10 @@
 #
 # See README for usage instructions.
 
+
 # We must use setuptools, not distutils, because we need to use the
 # namespace_packages option for the "google" package.
-from ez_setup import use_setuptools
-use_setuptools()
-
-from setuptools import setup
+from distutils.core import setup
 from distutils.spawn import find_executable
 import sys
 import os
@@ -31,13 +29,13 @@
   output = source.replace(".proto", "_pb2.py").replace("../src/", "")
 
   if not os.path.exists(source):
-    print "Can't find required file: " + source
+    print("Can't find required file: " + source)
     sys.exit(-1)
 
   if (not os.path.exists(output) or
       (os.path.exists(source) and
        os.path.getmtime(source) > os.path.getmtime(output))):
-    print "Generating %s..." % output
+    print("Generating %s..." % output)
 
     if protoc == None:
       sys.stderr.write(
@@ -107,8 +105,8 @@
   setup(name = 'protobuf',
         version = '2.2.1-pre',
         packages = [ 'google' ],
-        namespace_packages = [ 'google' ],
-        test_suite = 'setup.MakeTestSuite',
+        #namespace_packages = [ 'google' ],
+        #test_suite = 'setup.MakeTestSuite',
         # Must list modules explicitly so that we don't install tests.
         py_modules = [
           'google.protobuf.internal.containers',

Reply via email to