We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
YAML serialization raises an exception when a node disappears
https://github.com/translate/translate/blob/e5d4d38fbcc7fb310683e7b12f9ae7deab9d7788/translate/storage/yaml.py#L142

```Exception Value:	'str' object does not support item assignment```

In my case (through weblate), the existing file has:
```
it:
  base:
    path: Italian path
```

And a new node is used in the source translation (`base->path->sublevel`):
```
en:
  base:
    path:
      sublevel: Now I want these nested actually
```

The code in `serialize` will raise an exception on line 154 (and make the file empty). 

--- END ISSUE ---

Below are some code segments, each from a relevant file. One or more of these files may contain bugs.
--- BEGIN FILES ---
Path: `translate/storage/yaml.py`
Content:
```
1 # -*- coding: utf-8 -*-
2 #
3 # Copyright 2016 Michal Čihař
4 #
5 # This file is part of the Translate Toolkit.
6 #
7 # This program is free software; you can redistribute it and/or modify
8 # it under the terms of the GNU General Public License as published by
9 # the Free Software Foundation; either version 2 of the License, or
10 # (at your option) any later version.
11 #
12 # This program is distributed in the hope that it will be useful,
13 # but WITHOUT ANY WARRANTY; without even the implied warranty of
14 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15 # GNU General Public License for more details.
16 #
17 # You should have received a copy of the GNU General Public License
18 # along with this program; if not, see <http://www.gnu.org/licenses/>.
19 
20 r"""Class that manages YAML data files for translation
21 """
22 
23 from __future__ import absolute_import
24 from __future__ import unicode_literals
25 
26 import uuid
27 from collections import OrderedDict
28 
29 import six
30 import yaml
31 import yaml.constructor
32 
33 from translate.storage import base
34 
35 
36 class OrderedDictYAMLLoader(yaml.SafeLoader):
37     """
38     A YAML loader that loads mappings into ordered dictionaries.
39     """
40 
41     def __init__(self, *args, **kwargs):
42         yaml.SafeLoader.__init__(self, *args, **kwargs)
43 
44         self.add_constructor(u'tag:yaml.org,2002:map', type(self).construct_yaml_map)
45         self.add_constructor(u'tag:yaml.org,2002:omap', type(self).construct_yaml_map)
46 
47     def construct_yaml_map(self, node):
48         data = OrderedDict()
49         yield data
50         value = self.construct_mapping(node)
51         data.update(value)
52 
53     def construct_mapping(self, node, deep=False):
54         if isinstance(node, yaml.MappingNode):
55             self.flatten_mapping(node)
56         else:
57             raise yaml.constructor.ConstructorError(
58                 None, None,
59                 'expected a mapping node, but found %s' % node.id, node.start_mark
60             )
61 
62         mapping = OrderedDict()
63         for key_node, value_node in node.value:
64             key = self.construct_object(key_node, deep=deep)
65             try:
66                 hash(key)
67             except TypeError as exc:
68                 raise yaml.constructor.ConstructorError(
69                     'while constructing a mapping',
70                     node.start_mark,
71                     'found unacceptable key (%s)' % exc, key_node.start_mark
72                 )
73             value = self.construct_object(value_node, deep=deep)
74             mapping[key] = value
75         return mapping
76 
77 
78 class UnsortableList(list):
79     def sort(self, *args, **kwargs):
80         pass
81 
82 
83 class UnsortableOrderedDict(OrderedDict):
84     def items(self, *args, **kwargs):
85         return UnsortableList(OrderedDict.items(self, *args, **kwargs))
86 
87 
88 class YAMLDumper(yaml.SafeDumper):
89     def represent_unsorted(self, data):
90         return self.represent_dict(data.items())
91 
92 
93 YAMLDumper.add_representer(UnsortableOrderedDict, YAMLDumper.represent_unsorted)
94 
95 
96 class YAMLUnit(base.TranslationUnit):
97     """A YAML entry"""
98 
99     def __init__(self, source=None, **kwargs):
100         self._id = None
101         if source:
102             self.source = source
103         super(YAMLUnit, self).__init__(source)
104 
105     def getsource(self):
106         return self.target
107 
108     def setsource(self, source):
109         self.target = source
110     source = property(getsource, setsource)
111 
112     def setid(self, value):
113         self._id = value
114 
115     def getid(self):
116         # Ensure we have ID (for serialization)
117         if self._id is None:
118             self._id = str(uuid.uuid4())
119         return self._id
120 
121     def getlocations(self):
122         return [self.getid()]
123 
124 
125 class YAMLFile(base.TranslationStore):
126     """A YAML file"""
127 
128     UnitClass = YAMLUnit
129 
130     def __init__(self, inputfile=None, **kwargs):
131         """construct a YAML file, optionally reading in from inputfile."""
132         super(YAMLFile, self).__init__(**kwargs)
133         self.filename = ''
134         self._file = u''
135         if inputfile is not None:
136             self.parse(inputfile)
137 
138     def get_root_node(self, node):
139         """Returns root node for serialize"""
140         return node
141 
142     def serialize(self, out):
143         def nested_set(target, path, value):
144             if len(path) > 1:
145                 if len(path) == 2 and path[1][0] == '[' and path[1][-1] == ']' and path[1][1:-1].isdigit():
146                     if path[0] not in target:
147                         target[path[0]] = []
148                     target[path[0]].append(value)
149                 else:
150                     if path[0] not in target:
151                         target[path[0]] = UnsortableOrderedDict()
152                     nested_set(target[path[0]], path[1:], value)
153             else:
154                 target[path[0]] = value
155 
156         units = UnsortableOrderedDict()
157         for unit in self.unit_iter():
158             nested_set(units, unit.getid().split('->'), unit.target)
159         out.write(yaml.dump_all(
160             [self.get_root_node(units)],
161             Dumper=YAMLDumper,
162             default_flow_style=False, encoding='utf-8', allow_unicode=True
163         ))
164 
165     def _flatten(self, data, prev=""):
166         """Flatten YAML dictionary.
167         """
168         if isinstance(data, dict):
169             for k, v in six.iteritems(data):
170                 if not isinstance(k, six.string_types):
171                     raise base.ParseError(
172                         'Key not string: {0}/{1} ({2})'.format(prev, k, type(k))
173                     )
174 
175                 for x in self._flatten(v, '->'.join((prev, k)) if prev else k):
176                     yield x
177         else:
178             if isinstance(data, six.string_types):
179                 yield (prev, data)
180             elif isinstance(data, bool):
181                 yield (prev, str(data))
182             elif isinstance(data, list):
183                 for k, v in enumerate(data):
184                     key = '[{0}]'.format(k)
185                     yield ('->'.join((prev, key)), six.text_type(v))
186             elif data is None:
187                 pass
188             else:
189                 raise ValueError("We don't handle these values:\n"
190                                  "Type: %s\n"
191                                  "Data: %s\n"
192                                  "Previous: %s" % (type(data), data, prev))
193 
194     def preprocess(self, data):
195         """Preprocess hook for child formats"""
196         return data
197 
198     def parse(self, input):
199         """parse the given file or file source string"""
200         if hasattr(input, 'name'):
201             self.filename = input.name
202         elif not getattr(self, 'filename', ''):
203             self.filename = ''
204         if hasattr(input, "read"):
205             src = input.read()
206             input.close()
207             input = src
208         if isinstance(input, bytes):
209             input = input.decode('utf-8')
210         try:
211             self._file = yaml.load(input, OrderedDictYAMLLoader)
212         except yaml.YAMLError as e:
213             message = e.problem if hasattr(e, 'problem') else e.message
214             if hasattr(e, 'problem_mark'):
215                 message += ' {0}'.format(e.problem_mark)
216             raise base.ParseError(message)
217 
218         self._file = self.preprocess(self._file)
219 
220         for k, data in self._flatten(self._file):
221             unit = self.UnitClass(data)
222             unit.setid(k)
223             self.addunit(unit)
224 
225 
226 class RubyYAMLFile(YAMLFile):
227     """Ruby YAML file, it has language code as first node."""
228 
229     def preprocess(self, data):
230         if isinstance(data, OrderedDict) and len(data) == 1:
231             lang = list(data.keys())[0]
232             self.settargetlanguage(lang)
233             return data[lang]
234         return data
235 
236     def get_root_node(self, node):
237         """Returns root node for serialize"""
238         if self.targetlanguage is not None:
239             result = UnsortableOrderedDict()
240             result[self.targetlanguage] = node
241             return result
242         return node
243
```
--- END FILES ---

Please first localize the bug based on the issue statement, and then generate a patch according to the `git diff` format fenced by three backticks.

Here is an example:

```diff
diff --git a/examples/server_async.py b/examples/server_async.py
--- a/examples/server_async.py
+++ b/examples/server_async.py
@@ -313,4 +313,4 @@
 
 
 if __name__ == "__main__":
-    asyncio.run(run_async_server("."), debug=True)
+    asyncio.run(run_async_server(), debug=True)
diff --git a/examples/server_sync.py b/examples/server_sync.py
--- a/examples/server_sync.py
+++ b/examples/server_sync.py
@@ -313,5 +313,5 @@
 
 
 if __name__ == "__main__":
-    server = run_sync_server(".")
+    server = run_sync_server()
     server.shutdown()

```

diff --git a/translate/storage/yaml.py b/translate/storage/yaml.py
--- a/translate/storage/yaml.py
+++ b/translate/storage/yaml.py
@@ -147,7 +147,9 @@
                         target[path[0]] = []
                     target[path[0]].append(value)
                 else:
-                    if path[0] not in target:
+                    # Add empty dict in case there is value and we
+                    # expect dict
+                    if path[0] not in target or not isinstance(target[path[0]], dict):
                         target[path[0]] = UnsortableOrderedDict()
                     nested_set(target[path[0]], path[1:], value)
             else:

{"golden_diff": "diff --git a/translate/storage/yaml.py b/translate/storage/yaml.py\n--- a/translate/storage/yaml.py\n+++ b/translate/storage/yaml.py\n@@ -147,7 +147,9 @@\n                         target[path[0]] = []\n                     target[path[0]].append(value)\n                 else:\n-                    if path[0] not in target:\n+                    # Add empty dict in case there is value and we\n+                    # expect dict\n+                    if path[0] not in target or not isinstance(target[path[0]], dict):\n                         target[path[0]] = UnsortableOrderedDict()\n                     nested_set(target[path[0]], path[1:], value)\n             else:\n", "issue": "YAML serialization raises an exception when a node disappears\nhttps://github.com/translate/translate/blob/e5d4d38fbcc7fb310683e7b12f9ae7deab9d7788/translate/storage/yaml.py#L142\r\n\r\n```Exception Value:\t'str' object does not support item assignment```\r\n\r\nIn my case (through weblate), the existing file has:\r\n```\r\nit:\r\n  base:\r\n    path: Italian path\r\n```\r\n\r\nAnd a new node is used in the source translation (`base->path->sublevel`):\r\n```\r\nen:\r\n  base:\r\n    path:\r\n      sublevel: Now I want these nested actually\r\n```\r\n\r\nThe code in `serialize` will raise an exception on line 154 (and make the file empty). \n", "before_files": [{"content": "# -*- coding: utf-8 -*-\n#\n# Copyright 2016 Michal \u010ciha\u0159\n#\n# This file is part of the Translate Toolkit.\n#\n# This program is free software; you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation; either version 2 of the License, or\n# (at your option) any later version.\n#\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n# GNU General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program; if not, see <http://www.gnu.org/licenses/>.\n\nr\"\"\"Class that manages YAML data files for translation\n\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import unicode_literals\n\nimport uuid\nfrom collections import OrderedDict\n\nimport six\nimport yaml\nimport yaml.constructor\n\nfrom translate.storage import base\n\n\nclass OrderedDictYAMLLoader(yaml.SafeLoader):\n    \"\"\"\n    A YAML loader that loads mappings into ordered dictionaries.\n    \"\"\"\n\n    def __init__(self, *args, **kwargs):\n        yaml.SafeLoader.__init__(self, *args, **kwargs)\n\n        self.add_constructor(u'tag:yaml.org,2002:map', type(self).construct_yaml_map)\n        self.add_constructor(u'tag:yaml.org,2002:omap', type(self).construct_yaml_map)\n\n    def construct_yaml_map(self, node):\n        data = OrderedDict()\n        yield data\n        value = self.construct_mapping(node)\n        data.update(value)\n\n    def construct_mapping(self, node, deep=False):\n        if isinstance(node, yaml.MappingNode):\n            self.flatten_mapping(node)\n        else:\n            raise yaml.constructor.ConstructorError(\n                None, None,\n                'expected a mapping node, but found %s' % node.id, node.start_mark\n            )\n\n        mapping = OrderedDict()\n        for key_node, value_node in node.value:\n            key = self.construct_object(key_node, deep=deep)\n            try:\n                hash(key)\n            except TypeError as exc:\n                raise yaml.constructor.ConstructorError(\n                    'while constructing a mapping',\n                    node.start_mark,\n                    'found unacceptable key (%s)' % exc, key_node.start_mark\n                )\n            value = self.construct_object(value_node, deep=deep)\n            mapping[key] = value\n        return mapping\n\n\nclass UnsortableList(list):\n    def sort(self, *args, **kwargs):\n        pass\n\n\nclass UnsortableOrderedDict(OrderedDict):\n    def items(self, *args, **kwargs):\n        return UnsortableList(OrderedDict.items(self, *args, **kwargs))\n\n\nclass YAMLDumper(yaml.SafeDumper):\n    def represent_unsorted(self, data):\n        return self.represent_dict(data.items())\n\n\nYAMLDumper.add_representer(UnsortableOrderedDict, YAMLDumper.represent_unsorted)\n\n\nclass YAMLUnit(base.TranslationUnit):\n    \"\"\"A YAML entry\"\"\"\n\n    def __init__(self, source=None, **kwargs):\n        self._id = None\n        if source:\n            self.source = source\n        super(YAMLUnit, self).__init__(source)\n\n    def getsource(self):\n        return self.target\n\n    def setsource(self, source):\n        self.target = source\n    source = property(getsource, setsource)\n\n    def setid(self, value):\n        self._id = value\n\n    def getid(self):\n        # Ensure we have ID (for serialization)\n        if self._id is None:\n            self._id = str(uuid.uuid4())\n        return self._id\n\n    def getlocations(self):\n        return [self.getid()]\n\n\nclass YAMLFile(base.TranslationStore):\n    \"\"\"A YAML file\"\"\"\n\n    UnitClass = YAMLUnit\n\n    def __init__(self, inputfile=None, **kwargs):\n        \"\"\"construct a YAML file, optionally reading in from inputfile.\"\"\"\n        super(YAMLFile, self).__init__(**kwargs)\n        self.filename = ''\n        self._file = u''\n        if inputfile is not None:\n            self.parse(inputfile)\n\n    def get_root_node(self, node):\n        \"\"\"Returns root node for serialize\"\"\"\n        return node\n\n    def serialize(self, out):\n        def nested_set(target, path, value):\n            if len(path) > 1:\n                if len(path) == 2 and path[1][0] == '[' and path[1][-1] == ']' and path[1][1:-1].isdigit():\n                    if path[0] not in target:\n                        target[path[0]] = []\n                    target[path[0]].append(value)\n                else:\n                    if path[0] not in target:\n                        target[path[0]] = UnsortableOrderedDict()\n                    nested_set(target[path[0]], path[1:], value)\n            else:\n                target[path[0]] = value\n\n        units = UnsortableOrderedDict()\n        for unit in self.unit_iter():\n            nested_set(units, unit.getid().split('->'), unit.target)\n        out.write(yaml.dump_all(\n            [self.get_root_node(units)],\n            Dumper=YAMLDumper,\n            default_flow_style=False, encoding='utf-8', allow_unicode=True\n        ))\n\n    def _flatten(self, data, prev=\"\"):\n        \"\"\"Flatten YAML dictionary.\n        \"\"\"\n        if isinstance(data, dict):\n            for k, v in six.iteritems(data):\n                if not isinstance(k, six.string_types):\n                    raise base.ParseError(\n                        'Key not string: {0}/{1} ({2})'.format(prev, k, type(k))\n                    )\n\n                for x in self._flatten(v, '->'.join((prev, k)) if prev else k):\n                    yield x\n        else:\n            if isinstance(data, six.string_types):\n                yield (prev, data)\n            elif isinstance(data, bool):\n                yield (prev, str(data))\n            elif isinstance(data, list):\n                for k, v in enumerate(data):\n                    key = '[{0}]'.format(k)\n                    yield ('->'.join((prev, key)), six.text_type(v))\n            elif data is None:\n                pass\n            else:\n                raise ValueError(\"We don't handle these values:\\n\"\n                                 \"Type: %s\\n\"\n                                 \"Data: %s\\n\"\n                                 \"Previous: %s\" % (type(data), data, prev))\n\n    def preprocess(self, data):\n        \"\"\"Preprocess hook for child formats\"\"\"\n        return data\n\n    def parse(self, input):\n        \"\"\"parse the given file or file source string\"\"\"\n        if hasattr(input, 'name'):\n            self.filename = input.name\n        elif not getattr(self, 'filename', ''):\n            self.filename = ''\n        if hasattr(input, \"read\"):\n            src = input.read()\n            input.close()\n            input = src\n        if isinstance(input, bytes):\n            input = input.decode('utf-8')\n        try:\n            self._file = yaml.load(input, OrderedDictYAMLLoader)\n        except yaml.YAMLError as e:\n            message = e.problem if hasattr(e, 'problem') else e.message\n            if hasattr(e, 'problem_mark'):\n                message += ' {0}'.format(e.problem_mark)\n            raise base.ParseError(message)\n\n        self._file = self.preprocess(self._file)\n\n        for k, data in self._flatten(self._file):\n            unit = self.UnitClass(data)\n            unit.setid(k)\n            self.addunit(unit)\n\n\nclass RubyYAMLFile(YAMLFile):\n    \"\"\"Ruby YAML file, it has language code as first node.\"\"\"\n\n    def preprocess(self, data):\n        if isinstance(data, OrderedDict) and len(data) == 1:\n            lang = list(data.keys())[0]\n            self.settargetlanguage(lang)\n            return data[lang]\n        return data\n\n    def get_root_node(self, node):\n        \"\"\"Returns root node for serialize\"\"\"\n        if self.targetlanguage is not None:\n            result = UnsortableOrderedDict()\n            result[self.targetlanguage] = node\n            return result\n        return node\n", "path": "translate/storage/yaml.py"}], "after_files": [{"content": "# -*- coding: utf-8 -*-\n#\n# Copyright 2016 Michal \u010ciha\u0159\n#\n# This file is part of the Translate Toolkit.\n#\n# This program is free software; you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation; either version 2 of the License, or\n# (at your option) any later version.\n#\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n# GNU General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program; if not, see <http://www.gnu.org/licenses/>.\n\nr\"\"\"Class that manages YAML data files for translation\n\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import unicode_literals\n\nimport uuid\nfrom collections import OrderedDict\n\nimport six\nimport yaml\nimport yaml.constructor\n\nfrom translate.storage import base\n\n\nclass OrderedDictYAMLLoader(yaml.SafeLoader):\n    \"\"\"\n    A YAML loader that loads mappings into ordered dictionaries.\n    \"\"\"\n\n    def __init__(self, *args, **kwargs):\n        yaml.SafeLoader.__init__(self, *args, **kwargs)\n\n        self.add_constructor(u'tag:yaml.org,2002:map', type(self).construct_yaml_map)\n        self.add_constructor(u'tag:yaml.org,2002:omap', type(self).construct_yaml_map)\n\n    def construct_yaml_map(self, node):\n        data = OrderedDict()\n        yield data\n        value = self.construct_mapping(node)\n        data.update(value)\n\n    def construct_mapping(self, node, deep=False):\n        if isinstance(node, yaml.MappingNode):\n            self.flatten_mapping(node)\n        else:\n            raise yaml.constructor.ConstructorError(\n                None, None,\n                'expected a mapping node, but found %s' % node.id, node.start_mark\n            )\n\n        mapping = OrderedDict()\n        for key_node, value_node in node.value:\n            key = self.construct_object(key_node, deep=deep)\n            try:\n                hash(key)\n            except TypeError as exc:\n                raise yaml.constructor.ConstructorError(\n                    'while constructing a mapping',\n                    node.start_mark,\n                    'found unacceptable key (%s)' % exc, key_node.start_mark\n                )\n            value = self.construct_object(value_node, deep=deep)\n            mapping[key] = value\n        return mapping\n\n\nclass UnsortableList(list):\n    def sort(self, *args, **kwargs):\n        pass\n\n\nclass UnsortableOrderedDict(OrderedDict):\n    def items(self, *args, **kwargs):\n        return UnsortableList(OrderedDict.items(self, *args, **kwargs))\n\n\nclass YAMLDumper(yaml.SafeDumper):\n    def represent_unsorted(self, data):\n        return self.represent_dict(data.items())\n\n\nYAMLDumper.add_representer(UnsortableOrderedDict, YAMLDumper.represent_unsorted)\n\n\nclass YAMLUnit(base.TranslationUnit):\n    \"\"\"A YAML entry\"\"\"\n\n    def __init__(self, source=None, **kwargs):\n        self._id = None\n        if source:\n            self.source = source\n        super(YAMLUnit, self).__init__(source)\n\n    def getsource(self):\n        return self.target\n\n    def setsource(self, source):\n        self.target = source\n    source = property(getsource, setsource)\n\n    def setid(self, value):\n        self._id = value\n\n    def getid(self):\n        # Ensure we have ID (for serialization)\n        if self._id is None:\n            self._id = str(uuid.uuid4())\n        return self._id\n\n    def getlocations(self):\n        return [self.getid()]\n\n\nclass YAMLFile(base.TranslationStore):\n    \"\"\"A YAML file\"\"\"\n\n    UnitClass = YAMLUnit\n\n    def __init__(self, inputfile=None, **kwargs):\n        \"\"\"construct a YAML file, optionally reading in from inputfile.\"\"\"\n        super(YAMLFile, self).__init__(**kwargs)\n        self.filename = ''\n        self._file = u''\n        if inputfile is not None:\n            self.parse(inputfile)\n\n    def get_root_node(self, node):\n        \"\"\"Returns root node for serialize\"\"\"\n        return node\n\n    def serialize(self, out):\n        def nested_set(target, path, value):\n            if len(path) > 1:\n                if len(path) == 2 and path[1][0] == '[' and path[1][-1] == ']' and path[1][1:-1].isdigit():\n                    if path[0] not in target:\n                        target[path[0]] = []\n                    target[path[0]].append(value)\n                else:\n                    # Add empty dict in case there is value and we\n                    # expect dict\n                    if path[0] not in target or not isinstance(target[path[0]], dict):\n                        target[path[0]] = UnsortableOrderedDict()\n                    nested_set(target[path[0]], path[1:], value)\n            else:\n                target[path[0]] = value\n\n        units = UnsortableOrderedDict()\n        for unit in self.unit_iter():\n            nested_set(units, unit.getid().split('->'), unit.target)\n        out.write(yaml.dump_all(\n            [self.get_root_node(units)],\n            Dumper=YAMLDumper,\n            default_flow_style=False, encoding='utf-8', allow_unicode=True\n        ))\n\n    def _flatten(self, data, prev=\"\"):\n        \"\"\"Flatten YAML dictionary.\n        \"\"\"\n        if isinstance(data, dict):\n            for k, v in six.iteritems(data):\n                if not isinstance(k, six.string_types):\n                    raise base.ParseError(\n                        'Key not string: {0}/{1} ({2})'.format(prev, k, type(k))\n                    )\n\n                for x in self._flatten(v, '->'.join((prev, k)) if prev else k):\n                    yield x\n        else:\n            if isinstance(data, six.string_types):\n                yield (prev, data)\n            elif isinstance(data, bool):\n                yield (prev, str(data))\n            elif isinstance(data, list):\n                for k, v in enumerate(data):\n                    key = '[{0}]'.format(k)\n                    yield ('->'.join((prev, key)), six.text_type(v))\n            elif data is None:\n                pass\n            else:\n                raise ValueError(\"We don't handle these values:\\n\"\n                                 \"Type: %s\\n\"\n                                 \"Data: %s\\n\"\n                                 \"Previous: %s\" % (type(data), data, prev))\n\n    def preprocess(self, data):\n        \"\"\"Preprocess hook for child formats\"\"\"\n        return data\n\n    def parse(self, input):\n        \"\"\"parse the given file or file source string\"\"\"\n        if hasattr(input, 'name'):\n            self.filename = input.name\n        elif not getattr(self, 'filename', ''):\n            self.filename = ''\n        if hasattr(input, \"read\"):\n            src = input.read()\n            input.close()\n            input = src\n        if isinstance(input, bytes):\n            input = input.decode('utf-8')\n        try:\n            self._file = yaml.load(input, OrderedDictYAMLLoader)\n        except yaml.YAMLError as e:\n            message = e.problem if hasattr(e, 'problem') else e.message\n            if hasattr(e, 'problem_mark'):\n                message += ' {0}'.format(e.problem_mark)\n            raise base.ParseError(message)\n\n        self._file = self.preprocess(self._file)\n\n        for k, data in self._flatten(self._file):\n            unit = self.UnitClass(data)\n            unit.setid(k)\n            self.addunit(unit)\n\n\nclass RubyYAMLFile(YAMLFile):\n    \"\"\"Ruby YAML file, it has language code as first node.\"\"\"\n\n    def preprocess(self, data):\n        if isinstance(data, OrderedDict) and len(data) == 1:\n            lang = list(data.keys())[0]\n            self.settargetlanguage(lang)\n            return data[lang]\n        return data\n\n    def get_root_node(self, node):\n        \"\"\"Returns root node for serialize\"\"\"\n        if self.targetlanguage is not None:\n            result = UnsortableOrderedDict()\n            result[self.targetlanguage] = node\n            return result\n        return node\n", "path": "translate/storage/yaml.py"}]}