Eliminate some copypasta

This commit is contained in:
Adrian Sampson 2015-11-19 16:26:27 -08:00
parent f995ab38db
commit 69ffb83453

View file

@ -82,6 +82,17 @@ def load(s):
return out return out
def _safe_value(obj, key, value):
"""Check whether the `value` is safe to represent in YAML and trust as
returned from parsed YAML.
This ensures that values do not change their type when the user edits their
YAML representation.
"""
typ = obj._type(key)
return isinstance(typ, SAFE_TYPES) and isinstance(value, typ.model_type)
def flatten(obj, fields): def flatten(obj, fields):
"""Represent `obj`, a `dbcore.Model` object, as a dictionary for """Represent `obj`, a `dbcore.Model` object, as a dictionary for
serialization. Only include the given `fields` if provided; serialization. Only include the given `fields` if provided;
@ -93,9 +104,8 @@ def flatten(obj, fields):
# Format each value. # Format each value.
d = {} d = {}
for key in obj.keys(): for key in obj.keys():
typ = obj._type(key)
value = obj[key] value = obj[key]
if isinstance(typ, SAFE_TYPES) and isinstance(value, typ.model_type): if _safe_value(obj, key, value):
# A safe value that is faithfully representable in YAML. # A safe value that is faithfully representable in YAML.
d[key] = value d[key] = value
else: else:
@ -117,8 +127,7 @@ def apply(obj, data):
strings as values. strings as values.
""" """
for key, value in data.items(): for key, value in data.items():
typ = obj._type(key) if _safe_value(obj, key, value):
if isinstance(typ, SAFE_TYPES) and isinstance(value, typ.model_type):
# A safe value *stayed* represented as a safe type. Assign it # A safe value *stayed* represented as a safe type. Assign it
# directly. # directly.
obj[key] = value obj[key] = value