Install
pip install ez_yaml
Usage
import ez_yaml
ez_yaml.to_string({"thing": 1, "abc": [ 1,2,3 ]})
ez_yaml.to_object(string='''
thing: 1
abc:
- 1
- 2
- 3
''')
ez_yaml.to_file(
{"thing": 1, "abc": [ 1,2,3 ]},
file_path="./my_file.yaml",
)
Settings
import ez_yaml
ez_yaml.to_string(
{"thing": 1, "abc": [ 1,2,3 ]},
settings=dict(
safe=False,
width=None,
allow_duplicate_keys=True,
explicit_start=False,
explicit_end=False,
explict_null=True,
indent_mapping=3,
indent_sequence=2,
offset=0,
)
)
ez_yaml.to_file(
{"thing": 1, "abc": [ 1,2,3 ]},
file_path="./my_file.yaml",
settings=dict(
width=9999999999999,
explicit_start=True,
explicit_end=True,
)
)
Custom Yaml Tags Example
from ez_yaml import yaml
@yaml.register_class
class YourCustomClass:
yaml_tag = "!python/YourCustomClass"
def __init__(self, something):
self.something = something
@classmethod
def from_yaml(cls, constructor, node):
print(node.value.startswith("blah blah YourCustomClass(something:"))
return YourCustomClass(something=node.value[len("blah blah YourCustomClass(something:")-1:-1])
@classmethod
def to_yaml(cls, representer, object_of_this_class):
representation = f"blah blah YourCustomClass(something:{object_of_this_class.something})"
return representer.represent_scalar(
tag=cls.yaml_tag,
value=representation,
style=None,
anchor=None
)
data = [
YourCustomClass(['blah blah blah']),
YourCustomClass({"thing": "lorem ipsum"}),
]
output = ez_yaml.to_string(data)
yaml.load(output)