473,327 Members | 1,936 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,327 software developers and data experts.

optparse


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 ?

The next move after a parse_args is often to call
a method 'do_stuff' with the args and options and
I'd like to use a call such as:

do_stuff(args, **options)

This function signature is handy if you also need
sometimes to call 'do_stuff' from the Python interpreter.

Cheers,

SB

Jul 19 '05 #1
5 2532
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. However, if you need a dict, it's pretty
simple -- use vars() or .__dict__:

py> import optparse
py> p = optparse.OptionParser()
py> p.add_option('-x')
<Option at 0x11a01e8: -x>
py> options, args = p.parse_args(['-x', '0'])
py> options.x
'0'
py> vars(options)
{'x': '0'}
py> options.__dict__
{'x': '0'}

STeVe
Jul 19 '05 #2

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 ?
However, if you need a dict, it's pretty
simple -- use vars() or .__dict__:


Agreed. 100%.

SB

Jul 19 '05 #3
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/
Jul 19 '05 #4
Steven Bethard wrote:
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> o = ??? # convert to object???
...
py> o.x, o.y
('spam', 42)


"hard" == "slightly less easy"?

class Spam:
def __init__(self, d):
self.__dict__.update(d)

then

o = Spam(options)

or use the types module (if you have a classic class)
import types
class Spam: pass .... o = types.InstanceType(Spam, {"x": 5, "y": 10})
o.x 5


My guess is the original intent was to make the command-line
parameters act more like regular variables. They are easier
to type (x.abc vs. x["abc"]) and the syntax coloring is different.
Andrew
da***@dalkescientific.com

Jul 19 '05 #5
Andrew Dalke wrote:
Steven Bethard wrote:
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> o = ??? # convert to object???
...
py> o.x, o.y
('spam', 42)


"hard" == "slightly less easy"?


No, sorry, "hard" -> "harder". Typo. For simple cases like this, it's
obviously not difficult, though it does take more work than the opposite
direction.

If you didn't catch the old discussions about some of the details, I
think they're under something like "generic objects" or "namespace
objects". You can check the archives if you're interested.

STeVe
Jul 19 '05 #6

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

8
by: Hans-Joachim Widmaier | last post by:
I was really pleased when the Optik module found its way into the standard Python battery compartment, as it matched all my option parsing requirements. But, as always, there's really nothing that...
3
by: washu | last post by:
Hi, I'm was going through the module help located on http://docs.python.org/lib/optparse-store-action.html and I tried modifying it a tiny bit and things don't work. If someone could tell me...
7
by: Henry Ludemann | last post by:
I've been writing an optparse alternative (using getopt) that is at a stage where I'd be interested in people's opinions. It allows you to easily creating command line interfaces to existing...
5
by: Norbert Thek | last post by:
Hi I'm using Python 24 on Windows > (2k) Is there an easy way to convince optparse to accept newline in the helpstring? and more importand also in the 'desc' string. I tried everything (from...
3
by: Karlo Lozovina | last post by:
If I create a file with only one line: --- from optparse import OptionParser --- I get this when I try to run it from "DOS" prompt: Traceback (most recent call last): File "optparse.py",...
3
by: Bob | last post by:
I'd like to setup command line switches that are dependent on other switches, similar to what rpm does listed below. From the grammar below we see that the "query-options" are dependent on the...
0
by: Steven Bethard | last post by:
I feel like I must be reinventing the wheel here, so I figured I'd post to see what other people have been doing for this. In general, I love the optparse interface, but it doesn't do any checks...
1
by: Pupeno | last post by:
Hello, I am doing some extreme use of optparse, that is, extending it as explained on http://docs.python.org/lib/optparse-other-reasons-to-extend-optparse.html I have subclassed OptionParser and...
2
by: mbeachy | last post by:
Some rather unexpected behavior in the set_default/set_defaults methods for OptionParser that I noticed recently: <Option at 0x-483b3414: -r/--restart> {'restart': None} {'retart': False,...
0
by: Robert Kern | last post by:
Jeff Keasler wrote: If you code it up with unit tests and documentation, it has a good chance. But in the meantime, you can tell optparse to stop processing options using the standard "--"...
0
by: DolphinDB | last post by:
Tired of spending countless mintues downsampling your data? Look no further! In this article, you’ll learn how to efficiently downsample 6.48 billion high-frequency records to 61 million...
0
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
1
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: ArrayDB | last post by:
The error message I've encountered is; ERROR:root:Error generating model response: exception: access violation writing 0x0000000000005140, which seems to be indicative of an access violation...
1
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
1
by: Defcon1945 | last post by:
I'm trying to learn Python using Pycharm but import shutil doesn't work
1
by: Shællîpôpï 09 | last post by:
If u are using a keypad phone, how do u turn on JavaScript, to access features like WhatsApp, Facebook, Instagram....
0
by: af34tf | last post by:
Hi Guys, I have a domain whose name is BytesLimited.com, and I want to sell it. Does anyone know about platforms that allow me to list my domain in auction for free. Thank you
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.