Skip to content

Component schema property ordering regression in ApiSpec.to_yaml() method #768

@vorticity

Description

@vorticity

In apispec-5.1.1 schema property ordering in the yaml output matched the order of fields in the marshmallow schema, so long as you added a Meta() class to the schema, with an ordered=True attribute. As of apispec-5.2.0 the marshmallow schema field ordering is no longer respected - instead the schema property ordering is always alphabetical.

My workaround is to re-implement YamlDumper and _represent_dict() functionality that was in yaml_utils up to apispec-5.1.1 with an additional add_representer() call to ensure OrderedDict and dict instances are both ordered correctly and use this instead of the to_yaml() method:

def ordered_yaml_dump(data, stream=None, Dumper=SafeDumper, **kwds):
    class OrderedDumper(Dumper):
        pass

    def _represent_dict(dumper, data):
        return dumper.represent_mapping(yaml.resolver.BaseResolver.DEFAULT_MAPPING_TAG, data.items())

    OrderedDumper.add_representer(OrderedDict, _dict_representer)
    OrderedDumper.add_representer(dict, _dict_representer)
    return yaml.dump(data, stream, OrderedDumper, **kwds)

Related commit: 09dd98f

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions