From d2ec56336e9b42780bb0aa643ccac3e6da482c67 Mon Sep 17 00:00:00 2001 From: Jan Lindemann Date: Wed, 4 Jun 2025 04:55:32 +0200 Subject: [PATCH] ArgsContainer: Add add_argument() function add_argument() at the face of it looks much like ArgumentParser.add_argument(), but is a function, not a class method. It takes the ArgsContainer|ArgParser instance as first argument, then decides what type it is, and proceeds to use this knowledge to decide whether or not the argument to be added already has a definition. Signed-off-by: Jan Lindemann --- tools/python/jwutils/ArgsContainer.py | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) diff --git a/tools/python/jwutils/ArgsContainer.py b/tools/python/jwutils/ArgsContainer.py index a0aa7f5..5019701 100644 --- a/tools/python/jwutils/ArgsContainer.py +++ b/tools/python/jwutils/ArgsContainer.py @@ -1,5 +1,7 @@ # -*- coding: utf-8 -*- +import argparse + from collections import OrderedDict from jwutils.log import * @@ -60,3 +62,18 @@ class ArgsContainer: # export except: pass slog(prio, f'{name}: {val}', caller=caller) + +def add_argument(p: argparse.ArgumentParser|ArgsContainer, name: str, *args, **kwargs): # export + + key = name.strip('--').replace('-', '_') + if isinstance(p, ArgsContainer): + if key in p.keys(): + return + elif isinstance(p, argparse.ArgumentParser): + for action in p._actions: + if key == action.dest: + return + else: + raise Exception('Unknown type {type(p)} of {p} passed to add_argument()') + + p.add_argument(name, *args, **kwargs)