I define a union type in topic.thrift file, and generate gen-py. like this:
union Generic{
1: string s,
2: bool b,
3: i64 i,
4: double d}
struct Article{
1: string title,
2: string content,
3: Generic test}
and the serialize code like this:
transport_out = TTransport.TMemoryBuffer()
protocol_out = TBinaryProtocol.TBinaryProtocol(transport_out)
parse_item.write(protocol_out)
bytes = transport_out.getvalue()
the parse_item is a object of Article:
parse_item = Article()
parse_item.test = 1
no matter str, int, bool, or double value assigned to parse_item.test, I all get a error like this:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "gen-py/topic/ttypes.py", line 189, in write
self.test.write(oprot)
AttributeError: 'str' object has no attribute 'write'
I really don't know why? Anyone have ideas?
This is a tricky one. The problem is that the Python implementation leverages Python's dynamic typing. By assigning an int to the parse_item struct "test" attribute, you change its type to "int" (!). Surprising, but upon reflection sensible.
To get the right types for serialization you need to create a Generic instance and set test to it.
Here's a walk through with working code: