Nicu Stiurca <supernic2...@gmail.com> added the comment:

Eric:
I agree, that would be the obvious workaround. However, it turns that the way 
dest is set differs for optional and positional arguments. I alluded to this in 
my earlier message http://bugs.python.org/issue15125#msg163456

Specifically, it turns out that when the first argument to add_argument() 
starts with '-', it is interpreted as an optional argument and dest in 
_inferred_ from the first argument (eg, by stripping leading '-', and replacing 
remaining '-' with '_'). So supplying dest= to add_argument() overrides this 
heuristic.

But when the first argument to add_argument() does not start with a '-', dest 
becomes exactly the first argument, and supplying dest as a keyword argument 
like you suggest yields the exception I reported earlier.

Revisiting the documentation on dest 
(http://docs.python.org/dev/library/argparse.html#dest), this behavior is 
briefly and un-enlighteningly addressed in the first paragraph. The problem is 
that the paragraph suggests that dest can be explicitly set using keyword 
argument even for positional arguments; instead a ValueError is thrown as I 
have already mentioned.

I suppose that patching argparse to replace '-' with '_' for positional 
arguments may break existing code for anyone that has figured out they can get 
hyphenated positional arguments with getattr(), which would make it a risky 
patch. But patching the module to allow explicitly setting dest via keyword 
argument shouldn't hurt anybody.

For clarity, I recommend adding """(This conversion does NOT take place for 
positional arguments.)""" before the last sentence of paragraph 2 in the dest 
documentation.

Since I had no idea about using getattr, I bet others wouldn't figure it out 
either. I suggest also adding a simple example in the documentation for anybody 
that wants to use an invalid Python identifier as an argument. (Please don't 
say this is an invalid use case because eg, ssh has options -1, -2, -4, and -6.)

----------

_______________________________________
Python tracker <rep...@bugs.python.org>
<http://bugs.python.org/issue15125>
_______________________________________
_______________________________________________
Python-bugs-list mailing list
Unsubscribe: 
http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com

Reply via email to