Reject Conflicting Command Options before Starting the Work

Reject conflicting command options before starting work, inspect parser defaults and required choices, and verify failure paths without executing product side effects.

How can a command-line interface reject mutually inconsistent operation choices and ambiguous long-option abbreviations before invoking its work function?

Substantively revised October 23, 2026. Author interpretation, documented cases and hypothetical examples are distinguished below.

A command can explain its mistake after it has already started doing the wrong work. The error message may be accurate, yet the important boundary has been crossed. A conflicting request should be rejected before the action begins, rather than left for the action to interpret after it has produced consequences.

Direct answer

Define incompatible modes in the argument parser and finish parsing before dispatching the work function. For the controlled Python interface below, a required mutually exclusive group permits inspect or export, while choices restrict output format and full option names avoid abbreviation drift. Test invalid argument lists against a separate work marker, not just an exit code. Successful parsing establishes the declared syntax and selected values; it does not validate every business constraint, authorize a filesystem operation or prove execution safe. The experiment uses already tokenized lists and performs no real export.

Key takeaways

A parser specification can make an ambiguous operation choice explicit before action dispatch. Required and mutually exclusive describe different conditions: one prevents omission, while the other prevents selecting conflicting alternatives. Both conditions are needed for the particular two-mode interface tested here.

An exit code alone does not reveal whether work happened. Help can exit successfully without dispatching anything. An invalid request can exit with an error, but the surrounding program still needs a structure that puts work after parsing. The controlled marker tests that boundary directly.

An accepted integer is not automatically an acceptable business value. The fixture parses negative one as an integer because no nonnegative rule was declared. That control preserves the difference between syntactic conversion and the substantive constraints the application must actually enforce.

Definitions and relationships

An argument parser translates an argument sequence into the values and selections specified by an interface. A mutually exclusive group declares alternatives that should not be selected together. A required group adds the separate condition that at least one alternative must be present.

Dispatch is the application's decision to call the operation selected by those parsed values. Parsing and dispatch can be implemented next to each other, but they are distinct events. A parser cannot prevent side effects that an application performs before parsing or inside custom conversion actions.

An abbreviated long option is a shortened name accepted when the parser permits it and considers it unambiguous. Adding a new option can change whether an old abbreviation has a unique meaning. An interface requiring full long names avoids that particular dependency, without resolving every possible compatibility issue.

The problem with checking modes inside the action

Imagine a hypothetical local capture utility with two modes, inspect and export. A caller accidentally supplies both. If the program starts exporting and only later notices inspect was also selected, a correct diagnostic arrives too late to establish that no action was attempted.

A second caller omits the mode altogether. An implicit default might be convenient, but it could select a stronger operation than the caller intended. For this invented interface, the specification deliberately requires an explicit mode rather than making either action the fallback.

The useful decision is where these conditions become authoritative. If they define the operation selection, place them before dispatch and test the boundary. That does not mean every command needs required flags; it means a program should implement its actual mode policy explicitly rather than hope later branches will resolve contradictory intent.

Root cause: validation and action share an uncontrolled sequence

A command's main function often grows incrementally. Logging, resource acquisition, option checks and work can become interleaved. In that arrangement, a later validation failure may coexist with earlier effects, while a test asserting only the final exception misses what already happened.

The parser is useful because it can describe selected syntactic relationships in one place. Yet using a parser is not itself the boundary. The program still has to call the work function only after parsing and any additional semantic checks required by the actual action.

The repair is a visible sequence: construct a side-effect-free parser, obtain accepted values, apply remaining operation-specific conditions, then dispatch. The experiment isolates the first and final steps using an in-memory marker. It supplies no claim about custom actions, file handles or network work that were never present in the fixture.

Framework: the Parse-to-Action Boundary

The Parse-to-Action Boundary is the author's proposed method for inspecting a small command interface. Its components are Mode Contract, Value Contract, Dispatch Evidence and Evolution Control. It tests which requests can reach a simulated action rather than certifying an arbitrary command as secure.

Mode Contract defines absent, single and conflicting selections. State whether a mode is required and whether particular modes can coexist. In the fixture, inspect and export are alternatives, but repeating the identical store_true flag is not treated as selecting both alternatives.

Value Contract states defaults, choices and conversions. JSON is the chosen default format, text is another allowed format and the limit is converted to an integer. These rules should not silently imply an undeclared range constraint or a guarantee that a destination accepts the chosen representation.

Dispatch Evidence records whether the action boundary was crossed. The fixture appends a small marker only after parse_args returns. Invalid cases must leave that marker empty, while help is checked separately because its successful exit should not be interpreted as completed work.

Evolution Control tests a command before and after adding another option. If abbreviations are permitted, a once-unambiguous prefix may acquire another candidate. Test the actual compatibility rule instead of assuming that a shorter spelling is a permanent alias merely because an earlier parser accepted it.

Framework example and application

Supply inspect alone and confirm the expected defaults reach the marker. Supply inspect and export together and confirm an error occurs with no marker. Then supply an invalid format and inspect whether the parser rejects that value before the same boundary.

Apply the method to the entry point rather than an isolated helper whose caller might already have started work. A parser unit test can show a rejected argument sequence; an entry-point control must also show that the rejected request did not proceed to the intended action path.

Three documented mechanisms

Example 1: argparse describes groups, values and option spelling

Python's argparse reference documents required mutually exclusive groups, value choices, defaults and disabling long-option abbreviation. The controlled interface uses these public features with ordinary built-in conversion. It does not assume the parser enforces conditions the program has not declared. [S1]

The practical implication is to make the interface contract inspectable. A required group can reject omission, while format choices can reject an unsupported spelling. A parsed namespace is useful evidence about those conditions, but does not establish business authorization or the validity of every combination outside the specified rules.

Example 2: the tutorial makes conflicting alternatives concrete

Python's argparse tutorial demonstrates conflicting verbose and quiet choices and shows rejected combinations. That example documents a concrete relationship between mutually incompatible modes. The local study applies the same kind of relationship to invented inspect and export flags, rather than claiming a real exporter was exercised. [S2]

The distinction between example and action matters. A tutorial's diagnostic illustrates parser behavior; the experiment's separate marker establishes where its own simulated dispatch occurs. Neither source demonstrates the safety of a different command's actual file-writing implementation.

Example 3: the accepted design separates parsing from dispatch choices

PEP 389 records argparse's accepted design, including support for richer command interfaces such as subcommands. It is historical context for why a declarative parser can represent more than ad hoc flag scanning. Current Python 3.11 documentation and the recorded runtime govern the operations actually tested here. [S3]

This context also makes an alternative visible: a real interface might use explicit subcommands instead of required mode flags. The fixture is not a universal interface-design recommendation. Its value is that the chosen policy is explicit and its pre-dispatch failure cases can be reproduced.

Case study: accepted syntax without actual export

Python 3.11.9 executed an original parser fixture named capture. The parser declared inspect and export as a required mutually exclusive group, a format chosen from json and text with json as default, and an integer limit defaulting to three. Abbreviation was disabled in the primary configuration.

The test called the entry point with argument lists directly. It did not launch a shell or parse a quoted command string. After successful parsing, the entry point appended a dictionary containing mode, format and limit to an in-memory list. That append was the only simulated work action.

Inspect alone reached the marker once with mode inspect, format json and limit three. Export with format text and limit five reached it with those explicit values. These controls show the accepted selection and defaults. They do not establish that a file was inspected, an export was created or five records were processed.

Six invalid requests stayed before the marker

The fixture tested an absent mode, both modes, format xml, a non-integer limit spelled five, an unknown option and the abbreviated option exp. Each case exited with code two, produced a diagnostic and left the work marker empty.

The empty marker is important evidence about the entry-point structure. The script placed its simulated action after parsing, so a parser exit prevented that action. This conclusion does not extend to effects a different program performs before parsing or to custom parser actions that execute their own work.

The exact error text was retained in the report, but the acceptance claim does not depend on treating every wording detail as a permanent cross-version interface. The tested facts are the chosen rejection, exit and marker states under the recorded parser and runtime.

Help succeeded without dispatching work

Requesting help exited with code zero and displayed the full inspect and export names. It left the work marker empty. An automation that treats every zero exit as proof that the business operation ran would misinterpret this normal help path.

The control therefore separates successful interface assistance from completed work. A real product can report those outcomes in its own format, but it should not infer an export or inspection merely from the absence of an error code.

This does not make a help request an authorization bypass or a security test. The fixture contains no protected action. It simply records that success-shaped process status and actual dispatch evidence answer different questions.

Abbreviation meaning changed after an option was added

A separate parser enabled abbreviation and initially exposed export without explain. The shortened exp spelling selected export. Adding explain to that parser made the same spelling ambiguous, and the new call exited with code two without reaching its marker.

The full export name remained accepted after explain was added in the strict configuration. That control demonstrates the narrower compatibility benefit of requiring complete long names. It does not claim that all future interface changes are compatible or that a parser should never offer intentional documented aliases.

The failure depends on the actual option set. A unique prefix can stop being unique as an interface grows, so callers should not assume an accepted abbreviation is an explicit stable alias unless the application defines that contract separately.

Two limits on the validation claim

Repeating inspect twice was accepted and reached the marker once with the same selected mode. The exclusive group prevents selecting conflicting alternatives; it does not impose an exact-one-occurrence rule on that store_true flag.

Supplying negative one for the integer limit was also accepted because the fixture declared integer conversion but no nonnegative range condition. That observation is deliberately retained as a boundary control. If the application needs a positive limit, it must add and test that semantic requirement before dispatch.

All 32 assertions passed. They covered the accepted modes and defaults, six rejected cases, help, abbreviation drift, repeated identical flags and the undeclared range constraint. No real filesystem access, shell quoting, network action, permission check or process cancellation was evaluated.

Failure example: an error code hides an earlier action

Suppose a hypothetical exporter opens its destination before checking whether inspect and export conflict. The command can eventually exit with a clear error while having already touched a resource. A test that checks only code two would not establish the stronger claim that no work was attempted.

The fixture avoids that sequence by putting its marker after parsing. Its evidence is limited to that structure and the absence of a marker on rejected requests. To evaluate a real exporter, inspect where resources are acquired and add actual safe tests for the relevant effects rather than relabeling this local marker test as a filesystem guarantee.

Repair the control boundary first. Keep interface rejection ahead of the action it is meant to prevent, then test the actual entry point. A diagnostic is useful to the caller, but its accuracy does not undo consequences produced before the rejected condition became authoritative.

Common mistakes in command validation

One mistake is placing pure-looking conversions around effectful operations. A custom type handler that opens files can cross an action boundary during parsing itself. This study uses ordinary integer conversion and no file-opening parser feature, so its pre-dispatch conclusion must not be extended to those untested handlers.

Another mistake is forgetting the absent-mode case. Mutual exclusion alone prevents conflicting selections without necessarily requiring any selection. The invented specification needs an explicit mode, so the fixture includes required behavior and tests omission separately from the both-modes failure.

A third mistake is calling every accepted prefix an alias. The abbreviation control changes behavior when explain is introduced. A deliberate alias and an incidental unambiguous prefix have different compatibility implications, and callers need to know which form the product promises to support.

Finally, do not treat a parsed namespace as proof of safe execution. The negative-limit control demonstrates one undeclared semantic condition. Actual operations can also require permissions, valid resource states and other constraints that the parser cannot infer from successful conversion.

Counterargument: should a tiny script need this structure?

A small local script may need only a few arguments and a straightforward parser. There is no requirement to introduce a framework or complex class hierarchy merely to call parse_args before work. The useful structure can be a short visible sequence whose failure paths are easy to inspect.

The tradeoff concerns how much ambiguity the real operation can tolerate. A harmless read-only helper and a command that changes external state may need different semantic checks. This experiment does not classify every command or prescribe a permission flow. It demonstrates a bounded way to test declared interface conditions before a simulated action.

Use the simplest interface that expresses the actual policy. Subcommands, explicit choices or a mutually exclusive group can each be appropriate. The acceptance question is whether rejected requests stay before the intended action boundary, not whether the implementation resembles this example's exact flag arrangement.

Action plan: test the rejected path before adding effects

Write a small table of absent, valid and conflicting operation choices. State which values are defaults and which must be explicit. Include the semantic constraints that matter to the action so that a built-in conversion is not accidentally treated as the complete business rule.

Place an in-memory marker after parsing and any declared semantic validation. Supply tokenized argument lists directly and test omission, conflicting alternatives, unknown options, invalid choices and help. Assert the marker state alongside exit behavior; a code alone does not describe whether the action path was entered.

Test interface evolution with an added option that shares a prefix. Decide whether shortened names are intentionally supported or incidental. Use full names or documented aliases where that is the actual compatibility contract rather than assuming an old prefix remains unique.

Only then connect the real work implementation and evaluate its own constraints safely. Filesystem authorization, output correctness and external effects need separate evidence. The parser test remains useful, but its narrow passing result should stay visible rather than absorbing capabilities it did not exercise.

FAQ: parser rejection and action evidence

Does a mutually exclusive group require a mode automatically?

Not merely because its members conflict. The fixture explicitly makes the group required and separately tests omission. Required selection and rejection of conflicting alternatives are distinct conditions, even though they are expressed together in this interface.

What happens when inspect and export are both supplied?

The controlled call exits with code two, records a diagnostic and leaves the work marker empty. That demonstrates the declared conflict under Python 3.11.9 and the fixture's parse-before-marker structure. No actual export operation is present.

Does a zero exit prove the work ran?

No. The help control exits with zero while displaying interface assistance and leaving the marker empty. A product needing evidence of completed work must observe its actual operation outcome rather than infer it from every successful process status.

Why disable abbreviated long options?

The fixture chooses complete spellings to avoid its demonstrated prefix ambiguity after adding explain. This is a specific interface policy, not a universal rule against convenience. Intentional aliases can still be designed and documented separately from incidental unambiguous prefixes.

What changed when explain was added?

With abbreviation enabled, exp initially selected export. After explain existed, that same prefix became ambiguous and was rejected. The test makes option-set evolution visible without claiming that every newly added option necessarily breaks an earlier spelling.

Is a repeated inspect flag forbidden?

Not in the tested store_true configuration. Repeating it is accepted and selects the same mode once for dispatch. The group enforces incompatible alternatives; the article does not claim it counts flag occurrences or imposes a separate exact-once spelling rule.

Why was negative one accepted as a limit?

The fixture specifies integer conversion and no nonnegative range condition. Negative one is an integer, so parsing succeeds. If the real operation requires a positive limit, implement and test that additional rule before treating the resulting value as valid for the action.

Does choices validate the actual output format implementation?

It restricts the accepted format names in this parser. The experiment does not implement JSON or text export, so it establishes no claim about output bytes, schema or compatibility with a destination. A declared name and a correct serializer are different evidence.

Was shell quoting tested?

No. The script receives already tokenized argument lists directly. It does not execute a shell or test how a user's command string becomes those tokens. Shell interpretation and quoting concerns require their own actual environment and tests.

Can parsing itself perform side effects?

A different interface can define effectful custom handlers or open resources during parsing. This experiment avoids them. Its marker boundary therefore applies to the controlled entry point and should not be presented as a blanket no-side-effects guarantee for every argparse program.

Does successful parsing authorize file access?

No permission or filesystem authorization was tested. Parsing establishes only the declared argument relationships and values. An actual operation must satisfy its own resource and authorization requirements before performing work, independently of whether its options were syntactically accepted.

Why inspect the marker as well as stderr?

A diagnostic explains rejection, while the marker shows whether this simulated action path was entered. Checking both separates a helpful error message from the stronger execution-order claim. The report retains those observations independently for each invalid request.

Should every interface use required mode flags?

No. The fixture uses them to make its two-mode policy concrete. A real product might use subcommands or another design. The relevant requirement is an explicit operation-selection contract and a tested boundary before the selected action begins.

Did this test cancel a running operation?

No operation was started and then cancelled. Rejected requests remained before the in-memory marker in the controlled sequence. Stopping or undoing work already in progress is a different capability and is not established by these parser tests.

What is the first useful regression test?

Choose a request that must be rejected and assert it cannot reach a harmless action marker at the actual entry point. Then add accepted and help controls so absence of work is not confused with a broken dispatcher or a successful assistance path.

Recommended books

Python Cookbook, third edition, by David Beazley and Brian K. Jones, published by O'Reilly in May 2013, provides Python implementation context. Its official metadata was checked. Current parser claims come from versioned documentation and the recorded runtime, not an assertion that every recipe remains an exact current interface specification.

A Philosophy of Software Design, second edition, by John Ousterhout, released in July 2021, offers context for making important interface conditions explicit. The author's official page confirms that edition. The recommendation does not attribute this fixture or its numerical results to the book.

The Pragmatic Programmer, twentieth anniversary edition, by David Thomas and Andrew Hunt, published in September 2019, provides broader engineering context. Its verified publisher record supports the recommendation; no full-book reading or independent certification of the command's real-world execution is claimed.

Further exploration

Compare a CLI parser with structured-configuration validation. Both can reject declared invalid inputs, but they consume different representations and enforce different contracts. A JSON schema result does not establish the meaning of command-line abbreviations, and a parsed namespace does not validate an unrelated configuration document.

Also distinguish interface defaults from the operation they select. A default format appears as a concrete value even when the caller omits it. That selection needs to remain inspectable, while substantive output correctness belongs to the serializer or worker that eventually consumes the value.

The next useful review is the first line of real work in one command entry point. Trace backward and ask which rejection conditions are already authoritative there. Moving a valid check before that boundary can prevent a contradictory request from becoming an action, while preserving an honest account of the execution properties still untested.

Primary evidence sources

Related concepts: systems thinking, wealth structure, and the survival loop. Read the editorial policy and citation guide.