Write union using tuple with schema
MODIFY
fastavro/_write.pyx
fastavro/_write.pyx
@@ -502,11 +502,15 @@ cpdef write_union(bytearray fo, datum, schema):
cdef int32 most_fields
cdef int32 index
cdef int32 fields
+ cdef str schema_name = None
if isinstance(datum, tuple):
(name, datum) = datum
for index, candidate in enumerate(schema):
if extract_record_type(candidate) == 'record':
- if name == candidate["name"]:
+ schema_name = candidate["name"]
+ else:
+ schema_name = candidate
+ if name == schema_name:
break
else:
msg = 'provided union type name %s not found in schema %s' \

MODIFY
fastavro/_write_py.py
fastavro/_write_py.py
@@ -385,7 +385,10 @@ def write_union(fo, datum, schema):
(name, datum) = datum
for index, candidate in enumerate(schema):
if extract_record_type(candidate) == 'record':
- if name == candidate["name"]:
+ schema_name = candidate['name']
+ else:
+ schema_name = candidate
+ if name == schema_name:
break
else:
msg = 'provided union type name %s not found in schema %s' \

MODIFY
tests/test_fastavro.py
tests/test_fastavro.py
@@ -1237,3 +1237,42 @@ def test_regular_vs_ordered_dict_map_typeerror():
# be different, indicating the exception occurred at a different line
# number.
assert filtered_stacks[0] != filtered_stacks[1]
+
+
+def test_write_union_tuple_primitive():
+ '''
+ Test that when we can use tuple style of writing unions
+ (see function `write_union` in `_write`) with primitives
+ not only with records.
+ '''
+
+ schema = {
+ 'name': 'test_name',
+ 'namespace': 'test',
+ 'type': 'record',
+ 'fields': [
+ {
+ 'name': 'val',
+ 'type': ['string', 'int']
+ }
+ ]
+ }
+
+ data = [
+ {"val": ("int", 1)},
+ {"val": ("string", "string")},
+ ]
+
+ expected_data = [
+ {"val": 1},
+ {"val": "string"},
+ ]
+
+ new_file = MemoryIO()
+ fastavro.writer(new_file, schema, data)
+ new_file.seek(0)
+
+ new_reader = fastavro.reader(new_file)
+ new_records = list(new_reader)
+
+ assert new_records == expected_data

Write union using tuple with schema