Sébastien Boisgérault wrote:
Steven Bethard wrote:
Sébastien Boisgérault wrote:
Any idea why the 'options' object in
# optparse stuff
(options, args) = parser.parse_args()
is not/couldn't be a real dict ? Or why at least it
does not support dict's usual methods ?
Well, it's not a real dict because the original API intends it to be
used as object attributes.
Sure ;). But what are the pros of this choice ? The option __str__
mimicks the behavior of a dict. Why not a full interface support
of it ?
Well one reason might be that it's easy to convert from an object's
attributes to a dict, while it's hard to go the other direction:
py> options.x, options.y
('spam', 42)
py> vars(options) # convert to dict
{'y': 42, 'x': 'spam'}
versus
py> options['x'], options['y']
('spam', 42)
py> o = ??? # convert to object???
....
py> o.x, o.y
('spam', 42)
Though I had been working on a namespace module[1] with Nick Coghlan and
Carlos Ribeiro that provided such behavior:
py> options['x'], options['y']
('spam', 42)
py> o = namespace.Namespace(options)
py> o
Namespace(x='spam', y=42)
py> o.x, o.y
('spam', 42)
However, the namespace module is not part of the Python stdlib, so by
providing an object with attributes instead of a dict, optparse supports
(using only builtin functions) both users that want an object with
attributes and users that want a dict.
STeVe
[1]
http://namespace.python-hosting.com/