I wondered the same thing... and thought "singleton", but given you are intending to share arguments across modules... it makes sense if your create a base_argparse
module to share a singleton via base_argparse.ArgumentParser
, this can then be used as a drop in replacement for argparse.ArgumentParser
.
I did try Creating a singleton in Python but it seemed like overkill. (esp. if you want to share inter module)
Do let me know if you found a better way...
File: base_argparse.py
import argparse
_singleton=None
_description=""
def ArgumentParser(description=None, *arg_l, **arg_d):
global _singleton, _description
if description:
if _description: _description+=" & "+description
else: _description=description
if _singleton is None: _singleton=argparse.ArgumentParser(description=_description, *arg_l, **arg_d)
return _singleton
File: module_x.py
import sys
import base_argparse
parser = base_argparse.ArgumentParser(description='Module_X Arguments')
parser.add_argument('-x', action="store_true", default=False)
if __name__=="__main__":
opt_ns=parser.parse_args(sys.argv[1:])
print opt_ns,opt_ns.x
File: module_y.py
import sys
import base_argparse
parser = base_argparse.ArgumentParser(description='Module_Y Arguments')
parser.add_argument('-y', action="store", dest="y")
if __name__=="__main__":
opt_ns=parser.parse_args(sys.argv[1:])
print opt_ns,opt_ns.y
File: module_z.py
import sys
import base_argparse
parser = base_argparse.ArgumentParser(description='Module_Z Arguments')
parser.add_argument('-z', action="store", dest="z", type=int)
if __name__=="__main__":
opt_ns=parser.parse_args(sys.argv[1:])
print opt_ns,opt_ns.z
File: test_argparse.py
import sys
import base_argparse
# in main ...
parser = base_argparse.ArgumentParser(description='Test Arguments')
# then the matching load modules
import module_x,module_y,module_z
if __name__=="__main__":
parser.add_argument('-a', action="store_true", default=False)
parser.add_argument('-b', action="store", dest="b")
parser.add_argument('-c', action="store", dest="c", type=int)
opt_ns=parser.parse_args(sys.argv[1:])
print opt_ns,opt_ns.a,opt_ns.b,opt_ns.c,opt_ns.x,opt_ns.y,opt_ns.z
Test cases:
$ python test_argparse.py
Namespace(a=False, b=None, c=None, x=False, y=None, z=None) False None None False None None
$ python module_x.py -x
Namespace(x=True) True
$ python module_x.py -a -b 2 -c 3 -x -y 25 -z 26
usage: module_x.py [-h] [-x]
module_x.py: error: unrecognized arguments: -a -b 2 -c 3 -y 25 -z 26
$ python test_argparse.py -a -b 2 -c 3
Namespace(a=True, b='2', c=3, x=False, y=None, z=None) True 2 3 False None None
$ python test_argparse.py -x -y 25 -z 26
Namespace(a=False, b=None, c=None, x=True, y='25', z=26) False None None True 25 26
$ python test_argparse.py -a -b 2 -c 3 -x -y 25 -z 26
Namespace(a=True, b='2', c=3, x=True, y='25', z=26) True 2 3 True 25 26