diff --git a/openhtf/util/argv.py b/openhtf/util/argv.py index c6cd3d09a..c10288798 100644 --- a/openhtf/util/argv.py +++ b/openhtf/util/argv.py @@ -1,4 +1,20 @@ -"""Utilities for handling command line arguments.""" +"""Utilities for handling command line arguments. + +StoreInModule: + Enables emulating a gflags-esque API (flag affects global value), but one + doesn't necessarily need to use flags to set values. + + Example usage: + DEFAULT_VALUE = 0 + ARG_PARSER = argv.ModuleParser() + ARG_PARSER.add_argument( + '--override-value', action=argv.StoreInModule, + default=DEFAULT_VALUE, target='%s.DEFAULT_VALUE' % __name__) + + Then in an entry point (main() function), use that parser as a parent: + parser = argparse.ArgumentParser(parents=[other_module.ARG_PARSER]) + parser.parse_args() +""" import argparse @@ -19,5 +35,7 @@ def __init__(self, *args, **kwargs): def __call__(self, parser, namespace, values, option_string=None): if hasattr(self, '_proxy'): values = self._proxy(parser, namespace, values) - setattr(__import__(self._tgt_mod), self._tgt_attr, values) + base, mod = self._tgt_mod.rsplit('.', 1) + module = getattr(__import__(base, fromlist=[mod]), mod) + setattr(module, self._tgt_attr, values)