PyYaml - overwrite yaml file automatically with inserted argparse parametersYAML Configuration fileParse a...

Indicating multiple different modes of speech (fantasy language or telepathy)

Bob has never been a M before

Partial sums of primes

Lifted its hind leg on or lifted its hind leg towards?

What if somebody invests in my application?

Books on the History of math research at European universities

Proof of Lemma: Every integer can be written as a product of primes

Does "Dominei" mean something?

Visiting the UK as unmarried couple

I2C signal and power over long range (10meter cable)

Can I use my Chinese passport to enter China after I acquired another citizenship?

A known event to a history junkie

Can somebody explain Brexit in a few child-proof sentences?

What to do when my ideas aren't chosen, when I strongly disagree with the chosen solution?

Stereotypical names

Latex for-and in equation

Do all polymers contain either carbon or silicon?

Organic chemistry Iodoform Reaction

Why isn't KTEX's runway designation 10/28 instead of 9/27?

Could solar power be utilized and substitute coal in the 19th century?

Meta programming: Declare a new struct on the fly

Lightning Web Component - do I need to track changes for every single input field in a form

My boss asked me to take a one-day class, then signs it up as a day off

Should a half Jewish man be discouraged from marrying a Jewess?



PyYaml - overwrite yaml file automatically with inserted argparse parameters


YAML Configuration fileParse a config-file and add to command-line-arguments using argparse in PythonAutotools detect YAML libraryAttempt at Abstracted YAML Configuration LoaderBuild scripts driven from yaml fileUsing argparse with parameters defined in config fileSimple YAML-based config file parserConverting Logstash YAML style configuration file into ElasticSearch Logstash JSON style configPyYAML - Saving data to .yaml filesParse YAML file with nested parameters as a Python class object













-1












$begingroup$


what I am loading a yaml file and updating it with argparse. what is your feedback on how to update yaml parameters automatically without checking if a argparse parameter is None.
There are almost 20 configuration parameters that with this current version I have to put 20 if conditions.



the output of yaml.save_load is:



import os
import argparse
import yaml
import functools
import datetime

parser = argparse.ArgumentParser()
parser.add_argument(
"--config",
nargs="?",
type=str,
default="p.yml",
help="Configuration file to use",
)
parser.add_argument('--learning_rate', type=float, default=0.001, help='learning rate amount')

args = parser.parse_args()


def yaml_dump(file_path, data):
"""
Write data into yaml file in file_path
:param file_path:
:param data:
:return: void
"""
with open(file_path, 'w') as file_descriptor:
yaml.safe_dump(data, file_descriptor)


def yaml_loader(file_path):
"""
Load yaml file
:param file_path:
:return: yaml file configuration
"""
with open(file_path, "r") as file_descriptor:
return yaml.safe_load(file_descriptor)


cfg = yaml_loader(args.config)
if args.learning_rate is not None:
cfg['training']['optimizer']['lr'] = args.learning_rate


ts = str(datetime.datetime.now()).split(".")[0].replace(" ", "_")
ts = ts.replace(":", "_").replace("-", "_")
logdir = os.path.join("runs", os.path.basename(args.config)[:-4], ts)
yaml_dump(os.path.join(logdir, args.config.split('/')[-1]), cfg)


here is the content of p.yaml file:



model:
arch: fcn8s
data:
dataset: pascal
train_split: train
val_split: val
img_rows: 'same'
img_cols: 'same'
path: VOC/
sbd_path: VOC/benchmark_RELEASE/
training:
train_iters: 300000
batch_size: 1
val_interval: 1000
n_workers: 16
print_interval: 50
optimizer:
name: 'sgd'
lr: 1.0e-10
weight_decay: 0.0005
momentum: 0.99
loss:
name: 'cross_entropy'
size_average: False
lr_schedule:
resume: fcn8s_pascal_best_model.pkl









share|improve this question









New contributor




Majid Azimi is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.







$endgroup$








  • 2




    $begingroup$
    Welcome to Code Review! Code Review is a platform where you can get feedback from other users on working code. Questions on how to fix certain errors are better suited for Stack Overflow. See also How to ask.
    $endgroup$
    – Alex
    yesterday












  • $begingroup$
    @Alex I have updated the code with a working code. now I am asking other users about their feedback on how to make it more efficient. Is it still not suited for StackExchange?
    $endgroup$
    – Majid Azimi
    yesterday






  • 2




    $begingroup$
    There's a space before def yaml_dump please ensure that this code does run :)
    $endgroup$
    – Peilonrayz
    yesterday










  • $begingroup$
    @Peilonrayz it has been corrected.
    $endgroup$
    – Majid Azimi
    yesterday






  • 1




    $begingroup$
    Depending on how the file is used, PyYAML is not really suited for this kind of updating. If the file needs to stay as much the same as possible, e.g. when it is checked into a revision control system, you'll run into spurious changes, like the key order of mappings, loss of superfluous quotes, and if there had been comments those are lost as well. You also have to adhere to YAML 1.1 (replaced in 2009 by YAML 1.2, which PyYAML hasn't been updated to).
    $endgroup$
    – Anthon
    yesterday


















-1












$begingroup$


what I am loading a yaml file and updating it with argparse. what is your feedback on how to update yaml parameters automatically without checking if a argparse parameter is None.
There are almost 20 configuration parameters that with this current version I have to put 20 if conditions.



the output of yaml.save_load is:



import os
import argparse
import yaml
import functools
import datetime

parser = argparse.ArgumentParser()
parser.add_argument(
"--config",
nargs="?",
type=str,
default="p.yml",
help="Configuration file to use",
)
parser.add_argument('--learning_rate', type=float, default=0.001, help='learning rate amount')

args = parser.parse_args()


def yaml_dump(file_path, data):
"""
Write data into yaml file in file_path
:param file_path:
:param data:
:return: void
"""
with open(file_path, 'w') as file_descriptor:
yaml.safe_dump(data, file_descriptor)


def yaml_loader(file_path):
"""
Load yaml file
:param file_path:
:return: yaml file configuration
"""
with open(file_path, "r") as file_descriptor:
return yaml.safe_load(file_descriptor)


cfg = yaml_loader(args.config)
if args.learning_rate is not None:
cfg['training']['optimizer']['lr'] = args.learning_rate


ts = str(datetime.datetime.now()).split(".")[0].replace(" ", "_")
ts = ts.replace(":", "_").replace("-", "_")
logdir = os.path.join("runs", os.path.basename(args.config)[:-4], ts)
yaml_dump(os.path.join(logdir, args.config.split('/')[-1]), cfg)


here is the content of p.yaml file:



model:
arch: fcn8s
data:
dataset: pascal
train_split: train
val_split: val
img_rows: 'same'
img_cols: 'same'
path: VOC/
sbd_path: VOC/benchmark_RELEASE/
training:
train_iters: 300000
batch_size: 1
val_interval: 1000
n_workers: 16
print_interval: 50
optimizer:
name: 'sgd'
lr: 1.0e-10
weight_decay: 0.0005
momentum: 0.99
loss:
name: 'cross_entropy'
size_average: False
lr_schedule:
resume: fcn8s_pascal_best_model.pkl









share|improve this question









New contributor




Majid Azimi is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.







$endgroup$








  • 2




    $begingroup$
    Welcome to Code Review! Code Review is a platform where you can get feedback from other users on working code. Questions on how to fix certain errors are better suited for Stack Overflow. See also How to ask.
    $endgroup$
    – Alex
    yesterday












  • $begingroup$
    @Alex I have updated the code with a working code. now I am asking other users about their feedback on how to make it more efficient. Is it still not suited for StackExchange?
    $endgroup$
    – Majid Azimi
    yesterday






  • 2




    $begingroup$
    There's a space before def yaml_dump please ensure that this code does run :)
    $endgroup$
    – Peilonrayz
    yesterday










  • $begingroup$
    @Peilonrayz it has been corrected.
    $endgroup$
    – Majid Azimi
    yesterday






  • 1




    $begingroup$
    Depending on how the file is used, PyYAML is not really suited for this kind of updating. If the file needs to stay as much the same as possible, e.g. when it is checked into a revision control system, you'll run into spurious changes, like the key order of mappings, loss of superfluous quotes, and if there had been comments those are lost as well. You also have to adhere to YAML 1.1 (replaced in 2009 by YAML 1.2, which PyYAML hasn't been updated to).
    $endgroup$
    – Anthon
    yesterday
















-1












-1








-1





$begingroup$


what I am loading a yaml file and updating it with argparse. what is your feedback on how to update yaml parameters automatically without checking if a argparse parameter is None.
There are almost 20 configuration parameters that with this current version I have to put 20 if conditions.



the output of yaml.save_load is:



import os
import argparse
import yaml
import functools
import datetime

parser = argparse.ArgumentParser()
parser.add_argument(
"--config",
nargs="?",
type=str,
default="p.yml",
help="Configuration file to use",
)
parser.add_argument('--learning_rate', type=float, default=0.001, help='learning rate amount')

args = parser.parse_args()


def yaml_dump(file_path, data):
"""
Write data into yaml file in file_path
:param file_path:
:param data:
:return: void
"""
with open(file_path, 'w') as file_descriptor:
yaml.safe_dump(data, file_descriptor)


def yaml_loader(file_path):
"""
Load yaml file
:param file_path:
:return: yaml file configuration
"""
with open(file_path, "r") as file_descriptor:
return yaml.safe_load(file_descriptor)


cfg = yaml_loader(args.config)
if args.learning_rate is not None:
cfg['training']['optimizer']['lr'] = args.learning_rate


ts = str(datetime.datetime.now()).split(".")[0].replace(" ", "_")
ts = ts.replace(":", "_").replace("-", "_")
logdir = os.path.join("runs", os.path.basename(args.config)[:-4], ts)
yaml_dump(os.path.join(logdir, args.config.split('/')[-1]), cfg)


here is the content of p.yaml file:



model:
arch: fcn8s
data:
dataset: pascal
train_split: train
val_split: val
img_rows: 'same'
img_cols: 'same'
path: VOC/
sbd_path: VOC/benchmark_RELEASE/
training:
train_iters: 300000
batch_size: 1
val_interval: 1000
n_workers: 16
print_interval: 50
optimizer:
name: 'sgd'
lr: 1.0e-10
weight_decay: 0.0005
momentum: 0.99
loss:
name: 'cross_entropy'
size_average: False
lr_schedule:
resume: fcn8s_pascal_best_model.pkl









share|improve this question









New contributor




Majid Azimi is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.







$endgroup$




what I am loading a yaml file and updating it with argparse. what is your feedback on how to update yaml parameters automatically without checking if a argparse parameter is None.
There are almost 20 configuration parameters that with this current version I have to put 20 if conditions.



the output of yaml.save_load is:



import os
import argparse
import yaml
import functools
import datetime

parser = argparse.ArgumentParser()
parser.add_argument(
"--config",
nargs="?",
type=str,
default="p.yml",
help="Configuration file to use",
)
parser.add_argument('--learning_rate', type=float, default=0.001, help='learning rate amount')

args = parser.parse_args()


def yaml_dump(file_path, data):
"""
Write data into yaml file in file_path
:param file_path:
:param data:
:return: void
"""
with open(file_path, 'w') as file_descriptor:
yaml.safe_dump(data, file_descriptor)


def yaml_loader(file_path):
"""
Load yaml file
:param file_path:
:return: yaml file configuration
"""
with open(file_path, "r") as file_descriptor:
return yaml.safe_load(file_descriptor)


cfg = yaml_loader(args.config)
if args.learning_rate is not None:
cfg['training']['optimizer']['lr'] = args.learning_rate


ts = str(datetime.datetime.now()).split(".")[0].replace(" ", "_")
ts = ts.replace(":", "_").replace("-", "_")
logdir = os.path.join("runs", os.path.basename(args.config)[:-4], ts)
yaml_dump(os.path.join(logdir, args.config.split('/')[-1]), cfg)


here is the content of p.yaml file:



model:
arch: fcn8s
data:
dataset: pascal
train_split: train
val_split: val
img_rows: 'same'
img_cols: 'same'
path: VOC/
sbd_path: VOC/benchmark_RELEASE/
training:
train_iters: 300000
batch_size: 1
val_interval: 1000
n_workers: 16
print_interval: 50
optimizer:
name: 'sgd'
lr: 1.0e-10
weight_decay: 0.0005
momentum: 0.99
loss:
name: 'cross_entropy'
size_average: False
lr_schedule:
resume: fcn8s_pascal_best_model.pkl






python yaml






share|improve this question









New contributor




Majid Azimi is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.











share|improve this question









New contributor




Majid Azimi is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.









share|improve this question




share|improve this question








edited yesterday







Majid Azimi













New contributor




Majid Azimi is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.









asked yesterday









Majid AzimiMajid Azimi

992




992




New contributor




Majid Azimi is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.





New contributor





Majid Azimi is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.






Majid Azimi is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.








  • 2




    $begingroup$
    Welcome to Code Review! Code Review is a platform where you can get feedback from other users on working code. Questions on how to fix certain errors are better suited for Stack Overflow. See also How to ask.
    $endgroup$
    – Alex
    yesterday












  • $begingroup$
    @Alex I have updated the code with a working code. now I am asking other users about their feedback on how to make it more efficient. Is it still not suited for StackExchange?
    $endgroup$
    – Majid Azimi
    yesterday






  • 2




    $begingroup$
    There's a space before def yaml_dump please ensure that this code does run :)
    $endgroup$
    – Peilonrayz
    yesterday










  • $begingroup$
    @Peilonrayz it has been corrected.
    $endgroup$
    – Majid Azimi
    yesterday






  • 1




    $begingroup$
    Depending on how the file is used, PyYAML is not really suited for this kind of updating. If the file needs to stay as much the same as possible, e.g. when it is checked into a revision control system, you'll run into spurious changes, like the key order of mappings, loss of superfluous quotes, and if there had been comments those are lost as well. You also have to adhere to YAML 1.1 (replaced in 2009 by YAML 1.2, which PyYAML hasn't been updated to).
    $endgroup$
    – Anthon
    yesterday
















  • 2




    $begingroup$
    Welcome to Code Review! Code Review is a platform where you can get feedback from other users on working code. Questions on how to fix certain errors are better suited for Stack Overflow. See also How to ask.
    $endgroup$
    – Alex
    yesterday












  • $begingroup$
    @Alex I have updated the code with a working code. now I am asking other users about their feedback on how to make it more efficient. Is it still not suited for StackExchange?
    $endgroup$
    – Majid Azimi
    yesterday






  • 2




    $begingroup$
    There's a space before def yaml_dump please ensure that this code does run :)
    $endgroup$
    – Peilonrayz
    yesterday










  • $begingroup$
    @Peilonrayz it has been corrected.
    $endgroup$
    – Majid Azimi
    yesterday






  • 1




    $begingroup$
    Depending on how the file is used, PyYAML is not really suited for this kind of updating. If the file needs to stay as much the same as possible, e.g. when it is checked into a revision control system, you'll run into spurious changes, like the key order of mappings, loss of superfluous quotes, and if there had been comments those are lost as well. You also have to adhere to YAML 1.1 (replaced in 2009 by YAML 1.2, which PyYAML hasn't been updated to).
    $endgroup$
    – Anthon
    yesterday










2




2




$begingroup$
Welcome to Code Review! Code Review is a platform where you can get feedback from other users on working code. Questions on how to fix certain errors are better suited for Stack Overflow. See also How to ask.
$endgroup$
– Alex
yesterday






$begingroup$
Welcome to Code Review! Code Review is a platform where you can get feedback from other users on working code. Questions on how to fix certain errors are better suited for Stack Overflow. See also How to ask.
$endgroup$
– Alex
yesterday














$begingroup$
@Alex I have updated the code with a working code. now I am asking other users about their feedback on how to make it more efficient. Is it still not suited for StackExchange?
$endgroup$
– Majid Azimi
yesterday




$begingroup$
@Alex I have updated the code with a working code. now I am asking other users about their feedback on how to make it more efficient. Is it still not suited for StackExchange?
$endgroup$
– Majid Azimi
yesterday




2




2




$begingroup$
There's a space before def yaml_dump please ensure that this code does run :)
$endgroup$
– Peilonrayz
yesterday




$begingroup$
There's a space before def yaml_dump please ensure that this code does run :)
$endgroup$
– Peilonrayz
yesterday












$begingroup$
@Peilonrayz it has been corrected.
$endgroup$
– Majid Azimi
yesterday




$begingroup$
@Peilonrayz it has been corrected.
$endgroup$
– Majid Azimi
yesterday




1




1




$begingroup$
Depending on how the file is used, PyYAML is not really suited for this kind of updating. If the file needs to stay as much the same as possible, e.g. when it is checked into a revision control system, you'll run into spurious changes, like the key order of mappings, loss of superfluous quotes, and if there had been comments those are lost as well. You also have to adhere to YAML 1.1 (replaced in 2009 by YAML 1.2, which PyYAML hasn't been updated to).
$endgroup$
– Anthon
yesterday






$begingroup$
Depending on how the file is used, PyYAML is not really suited for this kind of updating. If the file needs to stay as much the same as possible, e.g. when it is checked into a revision control system, you'll run into spurious changes, like the key order of mappings, loss of superfluous quotes, and if there had been comments those are lost as well. You also have to adhere to YAML 1.1 (replaced in 2009 by YAML 1.2, which PyYAML hasn't been updated to).
$endgroup$
– Anthon
yesterday












1 Answer
1






active

oldest

votes


















1












$begingroup$

While you cannot iterate over a Namespace directly, you can parse it into a dictionary using vars and iterate over that, if you have a mapping from the argparse name to the path in the config file. The hardest part is using this path to get to the right level in the dictionary:



from argparse import Namespace

# Hard-code command line arguments instead of parsing them
args = Namespace(learning_rate=0.001)
# fake having read the config file
cfg = {"training": {"optimizer": {"lr": 0}}}
# mapping from argparse name to path in config file
cfg_path = {"learning_rate": ('training', 'optimizer', 'lr')}

for name, value in vars(args).items():
if value is None:
continue
# go down to right level
d = cfg
keys = cfg_path[name]
for key in keys[:-1]:
d = d[key]
# assign value, using the fact that dictionaries are mutable
d[keys[-1]] = value


This will override values where you have a default value in argparse that is not None, which may for example change the order in which elements appear in your dictionaries.






share|improve this answer









$endgroup$













    Your Answer





    StackExchange.ifUsing("editor", function () {
    return StackExchange.using("mathjaxEditing", function () {
    StackExchange.MarkdownEditor.creationCallbacks.add(function (editor, postfix) {
    StackExchange.mathjaxEditing.prepareWmdForMathJax(editor, postfix, [["\$", "\$"]]);
    });
    });
    }, "mathjax-editing");

    StackExchange.ifUsing("editor", function () {
    StackExchange.using("externalEditor", function () {
    StackExchange.using("snippets", function () {
    StackExchange.snippets.init();
    });
    });
    }, "code-snippets");

    StackExchange.ready(function() {
    var channelOptions = {
    tags: "".split(" "),
    id: "196"
    };
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function() {
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled) {
    StackExchange.using("snippets", function() {
    createEditor();
    });
    }
    else {
    createEditor();
    }
    });

    function createEditor() {
    StackExchange.prepareEditor({
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: false,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: null,
    bindNavPrevention: true,
    postfix: "",
    imageUploader: {
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    },
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    });


    }
    });






    Majid Azimi is a new contributor. Be nice, and check out our Code of Conduct.










    draft saved

    draft discarded


















    StackExchange.ready(
    function () {
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f216129%2fpyyaml-overwrite-yaml-file-automatically-with-inserted-argparse-parameters%23new-answer', 'question_page');
    }
    );

    Post as a guest















    Required, but never shown

























    1 Answer
    1






    active

    oldest

    votes








    1 Answer
    1






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    1












    $begingroup$

    While you cannot iterate over a Namespace directly, you can parse it into a dictionary using vars and iterate over that, if you have a mapping from the argparse name to the path in the config file. The hardest part is using this path to get to the right level in the dictionary:



    from argparse import Namespace

    # Hard-code command line arguments instead of parsing them
    args = Namespace(learning_rate=0.001)
    # fake having read the config file
    cfg = {"training": {"optimizer": {"lr": 0}}}
    # mapping from argparse name to path in config file
    cfg_path = {"learning_rate": ('training', 'optimizer', 'lr')}

    for name, value in vars(args).items():
    if value is None:
    continue
    # go down to right level
    d = cfg
    keys = cfg_path[name]
    for key in keys[:-1]:
    d = d[key]
    # assign value, using the fact that dictionaries are mutable
    d[keys[-1]] = value


    This will override values where you have a default value in argparse that is not None, which may for example change the order in which elements appear in your dictionaries.






    share|improve this answer









    $endgroup$


















      1












      $begingroup$

      While you cannot iterate over a Namespace directly, you can parse it into a dictionary using vars and iterate over that, if you have a mapping from the argparse name to the path in the config file. The hardest part is using this path to get to the right level in the dictionary:



      from argparse import Namespace

      # Hard-code command line arguments instead of parsing them
      args = Namespace(learning_rate=0.001)
      # fake having read the config file
      cfg = {"training": {"optimizer": {"lr": 0}}}
      # mapping from argparse name to path in config file
      cfg_path = {"learning_rate": ('training', 'optimizer', 'lr')}

      for name, value in vars(args).items():
      if value is None:
      continue
      # go down to right level
      d = cfg
      keys = cfg_path[name]
      for key in keys[:-1]:
      d = d[key]
      # assign value, using the fact that dictionaries are mutable
      d[keys[-1]] = value


      This will override values where you have a default value in argparse that is not None, which may for example change the order in which elements appear in your dictionaries.






      share|improve this answer









      $endgroup$
















        1












        1








        1





        $begingroup$

        While you cannot iterate over a Namespace directly, you can parse it into a dictionary using vars and iterate over that, if you have a mapping from the argparse name to the path in the config file. The hardest part is using this path to get to the right level in the dictionary:



        from argparse import Namespace

        # Hard-code command line arguments instead of parsing them
        args = Namespace(learning_rate=0.001)
        # fake having read the config file
        cfg = {"training": {"optimizer": {"lr": 0}}}
        # mapping from argparse name to path in config file
        cfg_path = {"learning_rate": ('training', 'optimizer', 'lr')}

        for name, value in vars(args).items():
        if value is None:
        continue
        # go down to right level
        d = cfg
        keys = cfg_path[name]
        for key in keys[:-1]:
        d = d[key]
        # assign value, using the fact that dictionaries are mutable
        d[keys[-1]] = value


        This will override values where you have a default value in argparse that is not None, which may for example change the order in which elements appear in your dictionaries.






        share|improve this answer









        $endgroup$



        While you cannot iterate over a Namespace directly, you can parse it into a dictionary using vars and iterate over that, if you have a mapping from the argparse name to the path in the config file. The hardest part is using this path to get to the right level in the dictionary:



        from argparse import Namespace

        # Hard-code command line arguments instead of parsing them
        args = Namespace(learning_rate=0.001)
        # fake having read the config file
        cfg = {"training": {"optimizer": {"lr": 0}}}
        # mapping from argparse name to path in config file
        cfg_path = {"learning_rate": ('training', 'optimizer', 'lr')}

        for name, value in vars(args).items():
        if value is None:
        continue
        # go down to right level
        d = cfg
        keys = cfg_path[name]
        for key in keys[:-1]:
        d = d[key]
        # assign value, using the fact that dictionaries are mutable
        d[keys[-1]] = value


        This will override values where you have a default value in argparse that is not None, which may for example change the order in which elements appear in your dictionaries.







        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered 15 hours ago









        GraipherGraipher

        26.4k54092




        26.4k54092






















            Majid Azimi is a new contributor. Be nice, and check out our Code of Conduct.










            draft saved

            draft discarded


















            Majid Azimi is a new contributor. Be nice, and check out our Code of Conduct.













            Majid Azimi is a new contributor. Be nice, and check out our Code of Conduct.












            Majid Azimi is a new contributor. Be nice, and check out our Code of Conduct.
















            Thanks for contributing an answer to Code Review Stack Exchange!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid



            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.


            Use MathJax to format equations. MathJax reference.


            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f216129%2fpyyaml-overwrite-yaml-file-automatically-with-inserted-argparse-parameters%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            Fairchild Swearingen Metro Inhaltsverzeichnis Geschichte | Innenausstattung | Nutzung | Zwischenfälle...

            Pilgersdorf Inhaltsverzeichnis Geografie | Geschichte | Bevölkerungsentwicklung | Politik | Kultur...

            Marineschifffahrtleitung Inhaltsverzeichnis Geschichte | Heutige Organisation der NATO | Nationale und...