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 <jan@janware.com>
This commit is contained in:
Jan Lindemann 2025-06-04 04:55:32 +02:00
commit d2ec56336e

View file

@ -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)