For Python 3.7, I am getting following error:
`ruamel.yaml.representer.RepresenterError: cannot represent an object: {'a': 3}`
For the following piece of code taken from answer for PyYAML - Saving data to .yaml files. How can I fix this error?
from ruamel.yaml import YAML
class Config(dict):
def __init__(self, filename, auto_dump=True):
self.filename = filename
self.auto_dump = auto_dump
self.changed = False
self.yaml = YAML()
self.yaml.preserve_quotes = True
# uncomment and adapt to your specific indentation
# self.yaml.indent(mapping=4, sequence=4, offset=2)
if os.path.isfile(filename):
with open(filename) as f:
# use super here to avoid unnecessary write
super(Config, self).update(self.yaml.load(f) or {})
def dump(self, force=False):
if not self.changed and not force:
return
with open(self.filename, "w") as f:
self.yaml.dump(self, f)
self.changed = False
# following methods unchanged from PyYAML example
def updated(self):
if self.auto_dump:
self.dump(force=True)
else:
self.changed = True
def __setitem__(self, key, value):
super(Config, self).__setitem__(key, value)
self.updated()
def __delitem__(self, key):
super(Config, self).__delitem__(key)
self.updated()
def update(self, kwargs):
super(Config, self).update(kwargs)
self.updated()
cfg = Config("test.yaml")
print(cfg)
cfg['a'] = 3 # <=Error occurs
print(cfg)
cfg.update({"b": 4})
cfg.update(c=5)
del cfg['a']
print(cfg)
Related:
my_dict[in_key][out_key] = 100
, is locally changed but is not saved into data? Please see: #68691990 – Thigmotaxis