(This is even easier to do if you've defined your own
OptionParser subclass with some standard options.)
On the assumption that this is usually a mistake, optparse
raises an exception (OptionConflictError) by default when
this happens. Since this is an easily-fixed programming error, you
shouldn't try to catch this exception--fix your mistake and get on
with life.
Sometimes, you want newer options to deliberately replace the option
strings used by older options. You can achieve this by calling:
parser.set_conflict_handler("resolve")
which instructs optparse to resolve option conflicts
intelligently.
Here's how it works: every time you add an option, optparse
checks for conflicts with previously-added options. If it finds any,
it invokes the conflict-handling mechanism you specify either to the
OptionParser constructor:
At this point, optparse detects that a previously-added option is already
using the -n option string. Since conflict_handler
== "resolve", it resolves the situation by removing -n
from the earlier option's list of option strings. Now,
--dry-run is the only way for the user to activate that
option. If the user asks for help, the help message will reflect
that, e.g.:
options:
--dry-run original dry-run option
...
-n, --noisy be noisy
Note that it's possible to whittle away the option strings for a
previously-added option until there are none left, and the user has no
way of invoking that option from the command-line. In that case,
optparse removes that option completely, so it doesn't show
up in help text or anywhere else. E.g. if we carry on with our
existing OptionParser:
At this point, the first -n/--dry-run
option is no longer accessible, so optparse removes it. If
the user asks for help, they'll get something like this:
options:
...
-n, --noisy be noisy
--dry-run new dry-run option