0

I am using solution in the related answer for How to auto-dump modified values in nested dictionaries using ruamel.yaml with RoundTripRepresenter.

If I make chnages on a list, ruamel.yaml is able to make changes on the local variable, but it does not dump/write the changes into the file. Would it be possible to achive it?

Example config file:

live:
- name: Ethereum
  networks:
  - chainid: 1
    explorer: https://api.etherscan.io/api

For example I changed name into alper and tried to append new item into the list.

my code:

class YamlUpdate:
    def __init__(self):
        self.config_file = Path.home() / "alper.yaml"
        self.network_config = Yaml(self.config_file)
        self.change_item()

    def change_item(self):
        for network in self.network_config["live"]:
            if network["name"] == "Ethereum":
                network["name"] = "alper"
                print(network)
                network.append("new_item")

yy = YamlUpdate()
print(yy.config_file.read_text())

output is where name remains unchanged on the original file:

{'name': 'alper', 'networks': [{'chainid': 1, 'explorer': 'https://api.etherscan.io/api'}]}
live:
- name: Ethereum
  networks:
  - chainid: 1
    explorer: https://api.etherscan.io/api
alper
  • 2,919
  • 9
  • 53
  • 102

1 Answers1

1

I think you should look at making a class SubConfigList that behaves like a list but notifies its parent (in the datastructure), like in the other answer where SubConfig notifies its parent.

You'll also need to make sure to represent SubConfigList as a sequence into the YAML document.

If you ever going to have list at the root of your data structure, you'll need to have list-like alternative to the dict-like Config. (Or document for the consumers/users of your code that the root always needs to be a mapping).

Anthon
  • 69,918
  • 32
  • 186
  • 246
  • Would it be possible to make a hybrid class that can handle `list` and `dict`? – alper Nov 21 '21 at 08:45
  • If I do your advice on your answer could `SubConfig` still used for `dict`? – alper Nov 22 '21 at 07:37
  • Yes you can make a hybrid class, but IMO more difficult than necessary, I would not attempt it if I were you. I don't understand why you need to as about `Subconfig`, of course you still need that as intelligent `dict`, but you might need to make it `SubConfigList` aware and vv. – Anthon Nov 22 '21 at 08:50
  • I may have think more complex to solve this. I just wanted to inser an item in to a list using ruamel, actually it shouldn't be `dict-like` – alper Nov 22 '21 at 13:52