Skip to content

Commit 49dd463

Browse files
authored
Follow-up for deterministic defaults (#27)
1 parent 7581009 commit 49dd463

2 files changed

Lines changed: 15 additions & 10 deletions

File tree

src/py_avro_schema/_schemas.py

Lines changed: 9 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1188,16 +1188,6 @@ def data(self, names: NamesType) -> JSONObj:
11881188
field_data["aliases"] = sorted(self.aliases)
11891189
if self.default != dataclasses.MISSING:
11901190
default_value = self.schema.make_default(self.default)
1191-
1192-
# When a field is a string, but it's default value produces a UUID-like, we do not pass through the UUID
1193-
# schema (which already sets an empty default). We need to catch here the strings that look like a UUID
1194-
# and set a deterministic default.
1195-
if (
1196-
Option.DETERMINISTIC_DEFAULTS in self.options
1197-
and isinstance(default_value, str)
1198-
and (_UUID_PATTERN.match(default_value) or is_valid_datetime(default_value))
1199-
):
1200-
default_value = ""
12011191
field_data["default"] = default_value
12021192
if self.docs and Option.NO_DOC not in self.options:
12031193
field_data["doc"] = self.docs
@@ -1232,6 +1222,15 @@ def _record_field(self, py_field: dataclasses.Field) -> RecordField:
12321222
default = py_field.default
12331223
if callable(py_field.default_factory): # type: ignore
12341224
default = py_field.default_factory() # type: ignore
1225+
# When a field is a string, but it's default value produces a UUID-like, we do not pass through the UUID
1226+
# schema (which already sets an empty default). We need to catch here the strings that look like a UUID
1227+
# and set a deterministic default.
1228+
if (
1229+
Option.DETERMINISTIC_DEFAULTS in self.options
1230+
and isinstance(default, str)
1231+
and (_UUID_PATTERN.match(default) or is_valid_datetime(default))
1232+
):
1233+
default = ""
12351234
aliases, actual_type = get_field_aliases_and_actual_type(py_field.type) # type: ignore
12361235
field_obj = RecordField(
12371236
py_type=actual_type, # type: ignore

tests/test_dataclass.py

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -953,6 +953,7 @@ def timestamp_millis() -> str:
953953
@dataclasses.dataclass
954954
class PyType:
955955
time: str = dataclasses.field(default_factory=lambda: timestamp_millis())
956+
version: str = "2017-01-01"
956957

957958
expected = {
958959
"type": "record",
@@ -963,6 +964,11 @@ class PyType:
963964
"type": "string",
964965
"default": "",
965966
},
967+
{
968+
"name": "version",
969+
"type": "string",
970+
"default": "2017-01-01",
971+
},
966972
],
967973
}
968974
assert_schema(PyType, expected, options=pas.Option.DETERMINISTIC_DEFAULTS)

0 commit comments

Comments
 (0)