def coerce_type(cls, obj, typedef=None, key_order=None, **kwargs): r"""Coerce objects of specific types to match the data type. Args: obj (object): Object to be coerced. typedef (dict, optional): Type defintion that object should be coerced to. Defaults to None. key_order (list, optional): Order or keys correpsonding to elements in a provided list or tuple. Defaults to None. **kwargs: Additional keyword arguments are metadata entries that may aid in coercing the type. Returns: object: Coerced object. Raises: RuntimeError: If obj is a list or tuple, but key_order is not provided. """ from yggdrasil.serialize import pandas2dict, numpy2dict, list2dict if isinstance(obj, pd.DataFrame): obj = pandas2dict(obj) elif isinstance(obj, np.ndarray) and (len(obj.dtype) > 0): obj = numpy2dict(obj) elif isinstance(obj, (list, tuple)) and (key_order is not None): obj = list2dict(obj, names=key_order) return obj
def test_numpy2dict(): r"""Test conversion of a numpy array to a dictionary and back.""" with pytest.raises(TypeError): serialize.numpy2dict(None) with pytest.raises(TypeError): serialize.dict2numpy(None) nele = 5 names = ["complex", "name", "number", "value"] dtypes = ['c16', 'S5', 'i8', 'f8'] dtype = np.dtype([(n, f) for n, f in zip(names, dtypes)]) arr_mix = np.zeros(nele, dtype) arr_mix['name'][0] = 'hello' test_arrs = [arr_mix, np.zeros(0, dtype)] np.testing.assert_array_equal(serialize.dict2numpy({}), np.array([])) for ans in test_arrs: d = serialize.numpy2dict(ans) # Sorted res = serialize.dict2numpy(d) np.testing.assert_array_equal(ans, res) # Provided res = serialize.dict2numpy(d, order=ans.dtype.names) np.testing.assert_array_equal(ans, res)