serhii.net

In the middle of the desert you can say anything you want

20 Jan 2025

argparse add arbitrary kwargs at the end

If no real config thingy is required/wanted, then this works (stolen from Parsing Dictionary-Like Key-Value Pairs Using Argparse in Python | Sumit’s Space)1:

def parse_args():
    class ParseKwargs(argparse.Action):
        def __call__(self, parser, namespace, values, option_string=None):
            setattr(namespace, self.dest, dict())
            for value in values:
                key, value = value.split("=")
                getattr(namespace, self.dest)[key] = value
    parser.add_argument("--no-pics", action="store_true", help="Predict only on videos")
	# ...

    parser.add_argument(
        "-k",
        "--kwargs",
        nargs="*",
        action=ParseKwargs,
        help="Additional inference params, e.g.: batch=128, conf=0.2.",
    )

  1. interesting mix of topics on that website ↩︎

Nel mezzo del deserto posso dire tutto quello che voglio.
comments powered by Disqus