[Python] Check if Python argparse used explicit CLI argument or default value?

Discussão em 'Python' iniciado por Stack, Julho 25, 2025.

  1. Stack

    Stack Membro Participativo

    I derive some settings from my parser that I latter store on disk to be reloaded again, during the reload I want to overwrite some values but keep the first ones, similar to new default values.

    I want to have a priority of args2 > args1 > default values, however I face the challenge on how to determine the highest priority, especially when I pass the default value explicitly in arg2, it should not fall back to args1, i.e. a simple comparison with the default is not sufficient.

    args1 = ["-a", "1", "--bar", "2"] # Run 1
    args2 = ["--bar", "default-bar", "-c", "3"] # Run 2, override bar with default
    args2_b = ["-c", "3"] # Run 2b, bar should be restored from Run 1

    # Equivalent full args for Run 2
    wanted = ["-a", "1", "--bar", "default-bar", "-c", "3"]
    wanted_b = ["-a", "1", "--bar", "2", "-c", "3"]

    from argparse import ArgumentParser

    parser = ArgumentParser()
    # required arguments without defaults can be present too
    parser.add_argument("--foo", "-a", default="default-foo")
    parser.add_argument("--bar", "-b", default="default-bar")
    parser.add_argument("--baz", "-c", default="default-baz")

    results1 = parser.parse_args(args1)
    print(results1) # Namespace(foo='1', bar='2', baz='default-baz')
    results2 = parser.parse_args(args1)
    print(results2) # Namespace(foo='default-foo', bar='default-bar', baz='2')

    # merge results
    # ...?


    I do not want to make things too complicated and hard to maintain, therefore manually looking at sys.argv does not look feasible (I have many arguments, shorthand codes, usage of dest, ...).
    I use tap Typed Argument Parser - if that info helps to find a better solution, also I would like to keep most of tap's features, i.e. to define most arguments in a class and keep meaningful default values there.


    TL;DR: how could I differentiate between these two cases in Run 2?

    # Run 1
    file.py -a 1 --bar 2
    # Run 2, that references some state from Run 1
    # Use passed value:
    file.py -c 3 --restore-run 1 --bar "default-bar"

    # Use value from Run 1
    file.py -c 3 --restore-run 1


    Related questions:


    Continue reading...

Compartilhe esta Página