From 2f231b3b1f99e6f08ea8b23fb54e5602efd53ab8 Mon Sep 17 00:00:00 2001 From: Fahrzin Hemmati Date: Thu, 28 Jul 2016 12:18:41 -0700 Subject: [PATCH] Fix incorrect behavior in argv.StoreInModule (#389) Also document it now that it works :) Previously, this would always try to set attributes in the openhtf module itself, not openhtf.util.logs or whichever module was correct. --- openhtf/util/argv.py | 22 ++++++++++++++++++++-- 1 file changed, 20 insertions(+), 2 deletions(-) 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)