Permalink
Browse files

Merge pull request #249 from matthew-brett/allow-mio-odict

NF: allow OrderedDict as input to savemat
  • Loading branch information...
2 parents 060f78e + cb30a6a commit dc41dee3587a7f28fd0bf4d46c0f26193bc4e72f @rgommers rgommers committed Jun 10, 2012
Showing with 25 additions and 10 deletions.
  1. +8 −5 scipy/io/matlab/mio5.py
  2. +17 −5 scipy/io/matlab/tests/test_mio.py
View
@@ -438,12 +438,15 @@ def to_writeable(source):
return source
if source is None:
return None
- # Objects that have dicts
- if hasattr(source, '__dict__'):
+ # Objects that implement mappings
+ is_mapping = (hasattr(source, 'keys') and hasattr(source, 'values') and
+ hasattr(source, 'items'))
+ # Objects that don't implement mappings, but do have dicts
+ if not is_mapping and hasattr(source, '__dict__'):
source = dict((key, value) for key, value in source.__dict__.items()
if not key.startswith('_'))
- # Mappings or object dicts
- if hasattr(source, 'keys'):
+ is_mapping = True
+ if is_mapping:
dtype = []
values = []
for field, value in source.items():
@@ -452,7 +455,7 @@ def to_writeable(source):
dtype.append((field,object))
values.append(value)
if dtype:
- return np.array( [tuple(values)] ,dtype)
+ return np.array([tuple(values)] ,dtype)
else:
return None
# Next try and convert to an array
@@ -516,11 +516,23 @@ def test_use_small_element():
def test_save_dict():
# Test that dict can be saved (as recarray), loaded as matstruct
- d = {'a':1, 'b':2}
- stream = BytesIO()
- savemat_future(stream, {'dict':d})
- stream.seek(0)
- vals = loadmat(stream)
+ dict_types = (dict,)
+ try:
+ from collections import OrderedDict
+ except ImportError:
+ pass
+ else:
+ dict_types += (OrderedDict,)
+ exp_arr = np.zeros((1, 1), dtype = [('a', object), ('b', object)])
+ exp_arr['a'] = 1
+ exp_arr['b'] = 2
+ for dict_type in dict_types:
+ d = dict_type(a=1, b=2)
+ stream = BytesIO()
+ savemat_future(stream, {'dict': d})
+ stream.seek(0)
+ vals = loadmat(stream)
+ assert_array_equal(vals['dict'], exp_arr)
def test_1d_shape():

0 comments on commit dc41dee

Please sign in to comment.