Ticket #79 (closed defect: wontfix)

Opened 5 months ago

Last modified 5 months ago

Multiple scalar values used as key creates Python hash error

Reported by: clay@shirky.com Assigned to: xi
Priority: normal Component: pyyaml
Severity: normal Keywords: load list tuple hash
Cc:

Description

The YAML specification suggests that a mapping can have a key made of more than one item, as in

? - Detroit Tigers
  - Chicago cubs
:
  - 2001-07-23

However, when that data is imported via yaml.load(), PyYAML exits with a yaml.constructor.ConstructorError?, saying "found unacceptable key (list objects are unhashable)"

Is there a way to force multi-value keys to be processed as tuples instead of lists?

Attachments

Change History

05/21/08 18:19:30 changed by xi

  • status changed from new to closed.
  • resolution set to wontfix.

Yes, it's possible, using a custom constructor for yaml mappings.

For example, the following script

import yaml

data = """
? - Detroit Tigers
  - Chicago cubs
:
  - 2001-07-23
"""

def construct_yaml_map(loader, node):
    pairs = [(tuple(key) if isinstance(key, list) else key, value)
             for (key, value) in loader.construct_pairs(node, deep=True)]
    return dict(pairs)

yaml.add_constructor(u'tag:yaml.org,2002:map',
                     construct_yaml_map)

print yaml.load(data)

produces

{('Detroit Tigers', 'Chicago cubs'): [datetime.date(2001, 7, 23)]}

Add/Change #79 (Multiple scalar values used as key creates Python hash error)




Change Properties
Action