Skip to content
This repository has been archived by the owner on Feb 19, 2020. It is now read-only.

Commit

Permalink
Merge pull request #32 from asottile/new_dict_order
Browse files Browse the repository at this point in the history
Produce ordered results for plain dict in py36+
  • Loading branch information
asottile authored May 23, 2019
2 parents 3d3756f + babfe4b commit 91e8868
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 0 deletions.
5 changes: 5 additions & 0 deletions aspy/yaml/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,12 @@
from __future__ import absolute_import
from __future__ import unicode_literals

import sys
from collections import OrderedDict

import yaml


MAP_TYPE = yaml.resolver.BaseResolver.DEFAULT_MAPPING_TAG


Expand All @@ -30,6 +32,9 @@ class OrderedDumper(getattr(yaml, 'CSafeDumper', yaml.SafeDumper)):


OrderedDumper.add_representer(OrderedDict, dump_map)
# in python3.6+, dicts have order by default
if sys.version_info >= (3, 6): # pragma: no cover (py36+)
OrderedDumper.add_representer(dict, dump_map)


def ordered_load(stream):
Expand Down
15 changes: 15 additions & 0 deletions tests/yaml_test.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,10 @@
from __future__ import absolute_import
from __future__ import unicode_literals

import sys

import aspy.yaml
import pytest


def test_ordered_load():
Expand Down Expand Up @@ -47,3 +50,15 @@ def test_ordered_dump():
'b: harp\n'
'd: darp\n'
)


@pytest.mark.xfail(sys.version_info < (3, 6), reason='py36+')
def test_ordered_dump_plain_dict_py36_plus():
ret = aspy.yaml.ordered_dump({'z': 1, 'a': 2, 'c': 3, 'b': 4, 'd': -1})
assert ret == (
'z: 1\n'
'a: 2\n'
'c: 3\n'
'b: 4\n'
'd: -1\n'
)

0 comments on commit 91e8868

Please sign in to comment.