diff --git a/lib/yaml/representer.py b/lib/yaml/representer.py index 808ca06d..de7e589c 100644 --- a/lib/yaml/representer.py +++ b/lib/yaml/representer.py @@ -110,7 +110,10 @@ def represent_mapping(self, tag, mapping, flow_style=None): mapping = list(mapping.items()) if self.sort_keys: try: - mapping = sorted(mapping) + if callable(self.sort_keys): + mapping = sorted(mapping, key=self.sort_keys) + else: + mapping = sorted(mapping) except TypeError: pass for item_key, item_value in mapping: diff --git a/tests/data/mapping.sort_vowels_first b/tests/data/mapping.sort_vowels_first new file mode 100644 index 00000000..4fec99c5 --- /dev/null +++ b/tests/data/mapping.sort_vowels_first @@ -0,0 +1,6 @@ +u: 1 +c: 2 +v: 3 +d: 4 +w: 5 +e: 6 diff --git a/tests/data/mapping.sorted_vowels_first b/tests/data/mapping.sorted_vowels_first new file mode 100644 index 00000000..8607acbd --- /dev/null +++ b/tests/data/mapping.sorted_vowels_first @@ -0,0 +1,6 @@ +e: 6 +u: 1 +c: 2 +d: 4 +v: 3 +w: 5 diff --git a/tests/lib/test_sort_keys_function.py b/tests/lib/test_sort_keys_function.py new file mode 100644 index 00000000..06ed80d0 --- /dev/null +++ b/tests/lib/test_sort_keys_function.py @@ -0,0 +1,41 @@ +import yaml +import sys +import functools + +_vowels = set(('a','e','i','o','u')) + +def sort_keys_vowels_first(a, b): + # params are (key,value) pairs + a=a[0] + b=b[0] + if (a in _vowels) == (b in _vowels): + return (a>b)-(a=(3,7): + assert dump_unsorted == input + assert dump_unsorted_safe == input + +test_sort_keys_function.unittest = ['.sort_vowels_first', '.sorted_vowels_first'] + +if __name__ == '__main__': + import test_appliance + test_appliance.run(globals()) diff --git a/tests/lib/test_yaml.py b/tests/lib/test_yaml.py index a5c10a38..22ad31d7 100644 --- a/tests/lib/test_yaml.py +++ b/tests/lib/test_yaml.py @@ -13,6 +13,7 @@ from test_recursive import * from test_input_output import * from test_sort_keys import * +from test_sort_keys_function import * from test_multi_constructor import * from test_schema import *