Skip to content

Handling to_yaml for StrEnum types #3

@ClimenteA

Description

@ClimenteA

In order to have some autocomplete on the data contract yaml file we need to overwrite and generate this json schema. Using Literal doesn't fill the json schema generated, StrEnum must be used to have some options on autocomplete.

# yaml-language-server: $schema=https://etc/data_contract_schema.json

Current to_yaml function doesn't handle StrEnum types and on loading the file/string it gives this error:

self = <yaml.loader.SafeLoader object at 0x7ca834e4f9e0>
node = SequenceNode(tag='tag:yaml.org,2002:python/object/apply:schemas.v2.data_contract_schema.DQMetric', value=[ScalarNode(tag='tag:yaml.org,2002:str', value='xam_custom')])

    def construct_undefined(self, node):
>       raise ConstructorError(None, None,
                "could not determine a constructor for the tag %r" % node.tag,
                node.start_mark)
E       yaml.constructor.ConstructorError: could not determine a constructor for the tag 'tag:yaml.org,2002:python/object/apply:schemas.v2.data_contract_schema.DQMetric'
E         in "<unicode string>", line 25, column 13:
E               metric: !!python/object/apply:schemas.v2 ... 
E                       ^

.venv/lib/python3.12/site-packages/yaml/constructor.py

The solution is to overwrite the to_yaml function model dump to mode=json

class DataContractSchema(OpenDataContractStandard):
    def to_yaml(self) -> str:
        data = self.model_dump(mode="json", exclude_defaults=True, exclude_none=True, by_alias=True)
        return yaml.dump(
            data,
            sort_keys=False,
            allow_unicode=True,
        )

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