write None value for nullable field
MODIFY
fastavro/writer.py
fastavro/writer.py
@@ -146,7 +146,6 @@ LONG_MAX_VALUE = (1 << 63) - 1
def validate(datum, schema):
"""Determine if a python datum is an instance of a schema."""
-
record_type = extract_record_type(schema)
if record_type == 'null':
@@ -239,9 +238,11 @@ def write_record(fo, datum, schema):
their schema."""
for field in schema['fields']:
name = field['name']
- if name not in datum and 'default' not in field:
+ if name not in datum and 'default' not in field and\
+ 'null' not in field['type']:
raise ValueError('no value and no default for %s' % name)
- write_data(fo, datum.get(name, field.get('default')), field['type'])
+ write_data(fo, datum.get(
+ name, field.get('default')), field['type'])
WRITERS = {
@@ -356,6 +357,7 @@ def acquaint_schema(schema, repo=None):
class Writer(object):
+
def __init__(self,
fo,
schema,

MODIFY
tests/test_fastavro.py
tests/test_fastavro.py
@@ -248,6 +248,29 @@ def test_default_values():
assert new_records == [{"default_field": "default_value"}]
+def test_nullable_values():
+ schema = {
+ "type": "record",
+ "fields": [{
+ "name": "nullable_field",
+ "type": ["string", "null"]
+ }, {
+ "name": "field",
+ "type": "string"
+ }
+ ]
+ }
+ new_file = MemoryIO()
+ records = [{"field": "val"}, {"field": "val", "nullable_field": "no_null"}]
+ fastavro.writer(new_file, schema, records)
+ new_file.seek(0)
+ new_reader = fastavro.reader(new_file)
+ new_records = list(new_reader)
+ print(new_records)
+ assert new_records == [{'nullable_field': None, 'field': 'val'}, {
+ 'nullable_field': 'no_null', 'field': 'val'}]
+
+
def test_boolean_roundtrip():
schema = {
"type": "record",

write None value for nullable field