optparse object population
Peter Otten
__peter__ at web.de
Thu Aug 5 03:30:18 EDT 2004
Eric O. Angell wrote:
> Is there a way to coerce optparse into populating an object for me?
If you are dealing with just one object you can provide a custom values
parameter:
<code>
import optparse
class Header(object):
def __init__(self):
self.foo = "default-foo"
self.bar = "default-bar"
def __str__(self):
values = ["%s=%r" % nv for nv in self.__dict__.items()]
return "%s(%s)" % (self.__class__.__name__, ", ".join(values))
__repr__ = __str__
p = optparse.OptionParser()
p.add_option("--foo")
p.add_option("--bar")
p.add_option("--baz")
header = Header()
options, args = p.parse_args(["--foo", "custom-foo", "--baz", "custom-baz"],
values=header)
print "options is header", options is header
# True
print "header", header
</code>
You can even expand that to work with nested objects, but it gets a little
messy and you are probably better off with Jeff Epler's approach here:
<code-continued>
# (insert above code here)
class Header2(Header):
def __setattr__(self, name, value):
if "." in name:
left, right = name.split(".", 1)
setattr(getattr(self, left), right, value)
else:
object.__setattr__(self, name, value)
header2 = Header2()
header2.nested = Header2() # I use the same class here because I'm
# lazy, not for technical reasons
p.add_option("--nested.foo")
options, args = p.parse_args(["--nested.foo", "hi there"], values=header2)
print options
</code-continued>
Especially, I have some doubts whether __setattr__("dotted.name", value)
will always be allowed.
Peter
More information about the Python-list
mailing list