More cleanup.
[python_utils.git] / argparse_utils.py
index 43536e460b7b4cc238c09d263bd36ae2b3b8f88e..045d882a2b6c4b18f4a27fd0267a65dd2b4444e4 100644 (file)
@@ -1,5 +1,7 @@
 #!/usr/bin/python3
 
+"""Helpers for commandline argument parsing."""
+
 import argparse
 import datetime
 import logging
@@ -8,7 +10,6 @@ from typing import Any
 
 from overrides import overrides
 
-
 # This module is commonly used by others in here and should avoid
 # taking any unnecessary dependencies back on them.
 
@@ -16,13 +17,28 @@ logger = logging.getLogger(__name__)
 
 
 class ActionNoYes(argparse.Action):
+    """An argparse Action that allows for commandline arguments like this:
+
+        cfg.add_argument(
+            '--enable_the_thing',
+            action=ActionNoYes,
+            default=False,
+            help='Should we enable the thing?'
+        )
+
+    This creates cmdline arguments:
+
+        --enable_the_thing
+        --no_enable_the_thing
+
+    """
     def __init__(self, option_strings, dest, default=None, required=False, help=None):
         if default is None:
             msg = 'You must provide a default with Yes/No action'
             logger.critical(msg)
             raise ValueError(msg)
         if len(option_strings) != 1:
-            msg = 'Only single argument is allowed with YesNo action'
+            msg = 'Only single argument is allowed with NoYes action'
             logger.critical(msg)
             raise ValueError(msg)
         opt = option_strings[0]
@@ -82,8 +98,8 @@ def valid_bool(v: Any) -> bool:
 
     try:
         return to_bool(v)
-    except Exception:
-        raise argparse.ArgumentTypeError(v)
+    except Exception as e:
+        raise argparse.ArgumentTypeError(v) from e
 
 
 def valid_ip(ip: str) -> str:
@@ -248,10 +264,10 @@ def valid_duration(txt: str) -> datetime.timedelta:
 
     try:
         secs = parse_duration(txt)
-    except Exception as e:
-        raise argparse.ArgumentTypeError(e)
-    finally:
         return datetime.timedelta(seconds=secs)
+    except Exception as e:
+        logger.exception(e)
+        raise argparse.ArgumentTypeError(e) from e
 
 
 if __name__ == '__main__':