Commits

Andy Mikhailenko  committed dfe08ae

Add default_value argument to unfold_list_of_dicts

  • Participants
  • Parent commits 052a882

Comments (0)

Files changed (2)

File monk/manipulation.py

     return merge_defaults(spec, data, mergers=mergers)
 
 
-def unfold_list_of_dicts(value, default_key):
+class UNDEFINED:
+    pass
+
+
+def unfold_list_of_dicts(value, default_key, default_value=UNDEFINED):
     """
     Converts given value to a list of dictionaries as follows:
 
     * ``[{...}]`` → ``[{...}]``
     * ``{...}``   → ``[{...}]``
     * ``'xyz'``   → ``[{default_key: 'xyz'}]``
+    * ``None``    → ``[{default_key: default_value}]``  (if specified)
+    * ``None``    → ``[]``
+
+    :param default_value:
+        only Unicode, i.e. `str` in Python 3.x and **only** `unicode` in Python 2.x
 
     """
     if value is None:
-        return []
+        if default_value is UNDEFINED:
+            return []
+        value = default_value
+
     if isinstance(value, dict):
         return [value]
+
     if isinstance(value, text_type):
         return [{default_key: value}]
+
     if isinstance(value, list):
         if not all(isinstance(x, dict) for x in value):
             def _fix(x):
                 return {default_key: x} if isinstance(x, text_type) else x
             return list(map(_fix, value))
+
     return value
 
 

File unittests/test_manipulation.py

         assert [{'x': 'a'}] == m.unfold_list_of_dicts(     t('a'), default_key='x')
         assert [{'x': 'a'}, {'x': 'b'}] == \
             m.unfold_list_of_dicts([{'x': 'a'}, t('b')], default_key='x')
+        assert [] == m.unfold_list_of_dicts(None, default_key='x')
+        assert [{'x': u'y'}] == m.unfold_list_of_dicts(None, default_key='x',
+                                                       default_value=u'y')
 
         # edge cases (may need revision)
         assert [{'x': 1}] == m.unfold_list_of_dicts({'x': 1}, default_key='y')