Failure to parse sequences as key

Issue #54 new
Lars Kellogg-Stedman
created an issue

I encountered a YAML file that contains syntax like the following:

? - 0
  - 100
: This is a sample.

While this is perfectly valid YAML, PyYAML chokes on it with:

yaml.constructor.ConstructorError: while constructing a mapping
  in "sample.yaml", line 1, column 1
found unacceptable key (unhashable type: 'list')
  in "sample.yaml", line 1, column 3

And this is of course the sequence argument to the ? indicator is producing a Python list, which can't be used as a dictionary key. What about just transforming lists into tuples if they are the key in a mapping object? E.g., like this:

diff --git a/lib/yaml/constructor.py b/lib/yaml/constructor.py
index 635faac..87192a5 100644
--- a/lib/yaml/constructor.py
+++ b/lib/yaml/constructor.py
@@ -124,8 +124,11 @@ class BaseConstructor(object):
                     node.start_mark)
         mapping = {}
         for key_node, value_node in node.value:
-            key = self.construct_object(key_node, deep=deep)
+            is_sequence = isinstance(key_node, SequenceNode)
+            key = self.construct_object(key_node, deep=deep or is_sequence)
             try:
+                if is_sequence:
+                    key = tuple(key)
                 hash(key)
             except TypeError, exc:
                 raise ConstructorError("while constructing a mapping", node.start_mark,

This permits PyYAML to correctly parse the given syntax...but I'm not familiar enough with PyYAML to know if this is going to break something else.

Comments (0)

  1. Log in to comment