Status: New
Labels: Type-Defect Priority-Medium

New issue 208 by kleptog: python: constructor does not type check scalar values

What steps will reproduce the problem?
1. Create a simple protocol file, such as (test.proto):

--- cut ---
message CompositeType {
    required int32 stamp = 1;
--- cut ---

2. compile the protocol to python using protoc.

3. Execute the following interactively:

In [1]: from test_pb2 import *

In [2]: c=CompositeType(stamp='foobar')

# Now we have a string in an integer field

In [3]: print c
stamp: foobar

# Serialisation blows up

In [4]: c.SerializeToString()
TypeError                                 Traceback (most recent call last)

/tmp/<ipython console> in <module>()

... lots of traceback data ...

TypeError: unsupported operand type(s) for &: 'str' and 'int'

What is the expected output? What do you see instead?

I expected the creation of the object to throw a TypeError exception. A direct assignment of the same value produces:

In [5]: c.stamp='foobar'
TypeError                                 Traceback (most recent call last)

... lots of traceback ...

TypeError: 'foobar' has type <type 'str'>, but expected one of: (<type 'int'>, <type 'long'>)

which is expected.

What version of the product are you using? On what operating system?

protobuf 2.3.0 on python 2.5 on Debian 5.0

Please provide any additional information below.

This is simply a case of the constructor being cute and bypassing the proper handlers for setting values. This can be solved by changing one line in Replace:

        self._fields[field] = field_value

in the final else: with

        setattr(self, field, field_value)

which will call the appropriate type checker.

Note that for non-scalar fields it doesn't type check either but because it uses MergeFrom you don't get exceptions from deep within the serialisation code, so I don't think that's as much of a problem.

You received this message because you are subscribed to the Google Groups "Protocol 
Buffers" group.
To post to this group, send email to
To unsubscribe from this group, send email to
For more options, visit this group at

Reply via email to