Merge pull request #498 from mckoss/feature/set-option

fix bug setting options programatically
This commit is contained in:
bdarnell 2012-05-06 21:43:25 -07:00
commit 625c6e052f
1 changed files with 10 additions and 5 deletions

View File

@ -193,7 +193,7 @@ def print_help(file=sys.stdout):
class _Options(dict): class _Options(dict):
"""Our global program options, an dictionary with object-like access.""" """Our global program options, a dictionary with object-like access."""
@classmethod @classmethod
def instance(cls): def instance(cls):
if not hasattr(cls, "_instance"): if not hasattr(cls, "_instance"):
@ -205,9 +205,14 @@ class _Options(dict):
return self[name].value() return self[name].value()
raise AttributeError("Unrecognized option %r" % name) raise AttributeError("Unrecognized option %r" % name)
def __setattr__(self, name, value):
if isinstance(self.get(name), _Option):
return self[name].set(value)
raise AttributeError("Unrecognized option %r" % name)
class _Option(object): class _Option(object):
def __init__(self, name, default=None, type=str, help=None, metavar=None, def __init__(self, name, default=None, type=basestring, help=None, metavar=None,
multiple=False, file_name=None, group_name=None): multiple=False, file_name=None, group_name=None):
if default is None and multiple: if default is None and multiple:
default = [] default = []
@ -229,7 +234,7 @@ class _Option(object):
datetime.datetime: self._parse_datetime, datetime.datetime: self._parse_datetime,
datetime.timedelta: self._parse_timedelta, datetime.timedelta: self._parse_timedelta,
bool: self._parse_bool, bool: self._parse_bool,
str: self._parse_string, basestring: self._parse_string,
}.get(self.type, self.type) }.get(self.type, self.type)
if self.multiple: if self.multiple:
self._value = [] self._value = []
@ -257,8 +262,8 @@ class _Option(object):
(self.name, self.type.__name__)) (self.name, self.type.__name__))
else: else:
if value != None and not isinstance(value, self.type): if value != None and not isinstance(value, self.type):
raise Error("Option %r is required to be a %s" % raise Error("Option %r is required to be a %s (%s given)" %
(self.name, self.type.__name__)) (self.name, self.type.__name__, type(value)))
self._value = value self._value = value
# Supported date/time formats in our options # Supported date/time formats in our options