argparse - option with optional value

Ben Finney ben+python at benfinney.id.au
Fri May 18 21:59:14 EDT 2012


Ben Finney <ben+python at benfinney.id.au> writes:

> Miki Tebeka <miki.tebeka at gmail.com> writes:
> > The way I'm doing it currently is:
> >     ...
> >     no_edit = 'no-edit'
> >     parser.add_argument('-e', '--edit', help='open editor on log', nargs='?',
> >                         default=no_edit)
>
> There is a built-in “no value specified” value in Python: the None
> singleton. The ‘argparse’ library uses this for the argument default
> already, so you don't need to fuss with your own special handling
> <URL:http://docs.python.org/library/argparse.html#default>.

Miki Tebeka <miki.tebeka at gmail.com> writes:

> The problem with this approach is that in both cases of not specifying
> -e and with -e with no argument the value of args.edit is None.

Okay. Then instead of a string, which has a chance of being used as the
actual value, I recommend you instead, make a guaranteed-unique sentinel
value::

    NO_EDITOR = object()
    parser.add_argument(
            '-e', '--edit', help='open editor on log', nargs='?',
            default=NO_EDITOR)

    # …

    if args.edit is not NO_EDITOR:
            # start the editor

-- 
 \      “I am too firm in my consciousness of the marvelous to be ever |
  `\       fascinated by the mere supernatural …” —Joseph Conrad, _The |
_o__)                                                     Shadow-Line_ |
Ben Finney



More information about the Python-list mailing list