| 1 | --- |
| 2 | title: "Optional-value argparse flags: dispatch on 'is not None', never truthiness" |
| 3 | date: 2026-07-12 |
| 4 | category: conventions |
| 5 | module: last30days-cli |
| 6 | problem_type: convention |
| 7 | component: tooling |
| 8 | severity: medium |
| 9 | applies_when: |
| 10 | - "Retrofitting an optional value onto an existing flag (nargs='?' + const), where old dispatch sites were written for a two-state flag" |
| 11 | - "Any flag or config key where a falsy value ('', 0, []) is a meaningful present-value distinct from absence" |
| 12 | - "Dependent/modifier flags whose behavior only applies when an anchor flag is present" |
| 13 | tags: |
| 14 | - argparse |
| 15 | - nargs-optional |
| 16 | - truthiness |
| 17 | - cli-flags |
| 18 | - dispatch |
| 19 | - dependent-flags |
| 20 | - silent-failure |
| 21 | - sentinel-values |
| 22 | related_components: |
| 23 | - testing_framework |
| 24 | --- |
| 25 | |
| 26 | # Optional-value argparse flags: dispatch on `is not None`, never truthiness |
| 27 | |
| 28 | ## Context |
| 29 | |
| 30 | PR #816 retrofitted an optional value onto the `--discover` flag in `skills/last30days/scripts/last30days.py`: |
| 31 | |
| 32 | ```python |
| 33 | parser.add_argument( |
| 34 | "--discover", |
| 35 | metavar="DOMAIN", |
| 36 | nargs="?", |
| 37 | const="", |
| 38 | default=None, |
| 39 | help=( |
| 40 | "Sweep river listings and rank the topics accelerating in a domain; " |
| 41 | "each survivor gets a full research pass. Bare --discover (no domain) " |
| 42 | "runs global trending across every feed's hot list" |
| 43 | ), |
| 44 | ) |
| 45 | ``` |
| 46 | |
| 47 | With `nargs="?"` plus `const=""` plus `default=None`, the flag is deliberately three-state: |
| 48 | |
| 49 | - flag absent -> `args.discover is None` -> normal research run |
| 50 | - bare `--discover` -> `args.discover == ""` -> global trending sweep (empty domain) |
| 51 | - `--discover X` -> `args.discover == "X"` -> domain-scoped discovery |
| 52 | |
| 53 | The near-miss: the pre-existing dispatch was `if args.discover:`. Under Python truthiness, `""` and `None` are both falsy, so bare `--discover` would have been indistinguishable from no flag at all. The headline new mode of the PR (global trending) would simply never fire - the run would silently route into the normal-research path with no error, no warning, and no failing test unless a test exercised the bare form specifically. This was caught during development and the dispatch was changed to key on flag presence. |
| 54 | |
| 55 | A second, related trap was caught in PR review (Greptile P2): the dependent flag `--discover-shallow` was accepted without `--discover` and silently no-opped into a full research run - the user asked for a fast, thin sweep and got a slow, full one. It was fixed with an explicit guard that errors loudly (exit 2). |
| 56 | |
| 57 | ## Guidance |
| 58 | |
| 59 | 1. With `nargs="?"` + `const`, the None/const/value trichotomy IS the contract: absent = `None`, bare flag = the `const` value, valued = the user's string. Dispatch on `args.flag is not None` (flag present), never on truthiness. When retrofitting optionality onto an existing flag, grep EVERY existing reference to `args.<flag>` - the old references were written when the flag was two-state and any `if args.flag:` among them is now a latent misroute. |
| 60 | |
| 61 | 2. Put a comment at the dispatch site explaining why it uses `is not None`. `if args.flag:` looks like the idiomatic form, and a future "simplification" pass will happily rewrite the correct check back into the bug. The repo's dispatch carries exactly this comment (`skills/last30days/scripts/last30days.py`): |
| 62 | |
| 63 | ```python |
| 64 | # Bare --discover (no domain) is global trending, so the dispatch keys on |
| 65 | # "flag present" (is not None), never on the domain string's truthiness. |
| 66 | if args.discover is not None: |
| 67 | ``` |
| 68 | |
| 69 | 3. Dependent/modifier flags (`--x-modifier` that only applies with `--x`) must error loudly when their anchor flag is absent - never silently no-op. A silent no-op means the user asked for one mode and got another with zero feedback. Reject with a clear message and a nonzero exit: |
| 70 | |
| 71 | ```python |
| 72 | if args.discover_shallow: |
| 73 | # Without --discover this flag would silently no-op into a full |
| 74 | # research run - reject it instead of ignoring the requested mode. |
| 75 | sys.stderr.write( |
| 76 | "[last30days] --discover-shallow only applies to --discover runs; " |
| 77 | "add --discover [domain] or drop the flag.\n" |
| 78 | ) |
| 79 | return 2 |
| 80 | ``` |
| 81 | |
| 82 | 4. Pin both behaviors with CLI-level subprocess tests. Unit tests of the parser alone would not have caught the misroute, because parsing was correct - the bug lived in dispatch. The tests must run the real entry point end to end: one asserting the bare form reaches the new mode, one asserting the orphaned dependent flag is rejected (see Examples). |
| 83 | |
| 84 | ## Why This Matters |
| 85 | |
| 86 | The failure mode is silent misrouting, which is the worst kind: the feature ships, `--help` documents the bare form, and every invocation of it quietly runs the wrong mode. There is no exception, no error message, no test failure - the output is a plausible-looking result from the wrong pipeline. Nothing surfaces the bug unless a test (or an alert user) exercises the bare form specifically and checks which mode actually ran. The same is true of the dependent-flag no-op: `--discover-shallow` without `--discover` produced a valid full research run, just not the one the user asked for. |
| 87 | |
| 88 | ## When to Apply |
| 89 | |
| 90 | - Retrofitting an optional value onto an existing flag (`action="store_true"` or a plain valued option becoming `nargs="?"`): audit every dispatch site that reads the flag. |
| 91 | - Any flag where a falsy value (`""`, `0`, `[]`) is a MEANINGFUL present-value distinct from absence - the sentinel-vs-truthiness distinction applies beyond argparse (env vars, config keys, JSON fields). |
| 92 | - Dependent/modifier flags whose behavior only applies when an anchor flag is present. |
| 93 | |
| 94 | ## Examples |
| 95 | |
| 96 | Before (the near-miss - conflates bare flag with no flag): |
| 97 | |
| 98 | ```python |
| 99 | if args.discover: # '' and None are both falsy: bare --discover falls through |
| 100 | return _run_discover(args, config) |
| 101 | ``` |
| 102 | |
| 103 | After (`skills/last30days/scripts/last30days.py`, with the drift-guard comment): |
| 104 | |
| 105 | ```python |
| 106 | # Bare --discover (no domain) is global trending, so the dispatch keys on |
| 107 | # "flag present" (is not None), never on the domain string's truthiness. |
| 108 | if args.discover is not None: |
| 109 | if topic: |
| 110 | sys.stderr.write( |
| 111 | "[last30days] --discover supplies the domain and cannot be combined " |
| 112 | "with a positional topic.\n" |
| 113 | ) |
| 114 | return 2 |
| 115 | if args.drill: |
| 116 | sys.stderr.write("[last30days] --discover and --drill are mutually exclusive.\n") |
| 117 | return 2 |
| 118 | return _run_discover(args, config) |
| 119 | ``` |
| 120 | |
| 121 | The dependent-flag guard immediately below the dispatch: |
| 122 | |
| 123 | ```python |
| 124 | if args.discover_shallow: |
| 125 | # Without --discover this flag would silently no-op into a full |
| 126 | # research run - reject it instead of ignoring the requested mode. |
| 127 | sys.stderr.write( |
| 128 | "[last30days] --discover-shallow only applies to --discover runs; " |
| 129 | "add --discover [domain] or drop the flag.\n" |
| 130 | ) |
| 131 | return 2 |
| 132 | ``` |
| 133 | |
| 134 | The two pinning tests in `tests/test_discover_mode.py`, both running the real CLI via subprocess: |
| 135 | |
| 136 | ```python |
| 137 | def test_discovery_cli_bare_discover_is_global_trending(): |
| 138 | """Bare --discover (no domain) must run global trending, not error.""" |
| 139 | result = subprocess.run( |
| 140 | [ |
| 141 | sys.executable, |
| 142 | "skills/last30days/scripts/last30days.py", |
| 143 | "--discover", |
| 144 | "--mock", |
| 145 | "--emit=json", |
| 146 | ], |
| 147 | cwd=REPO_ROOT, |
| 148 | capture_output=True, |
| 149 | text=True, |
| 150 | check=False, |
| 151 | ) |
| 152 | assert result.returncode == 0, result.stderr |
| 153 | payload = json.loads(result.stdout) |
| 154 | assert payload["kind"] == "discovery" |
| 155 | assert payload["domain"] == "" |
| 156 | assert payload["outcome"] in {"ok", "nothing-solid"} |
| 157 | |
| 158 | |
| 159 | def test_discovery_cli_rejects_shallow_without_discover(): |
| 160 | """--discover-shallow on a normal topic run must error, not silently no-op |
| 161 | into a full research pass (P2 from PR #816 review).""" |
| 162 | result = subprocess.run( |
| 163 | [ |
| 164 | sys.executable, |
| 165 | "skills/last30days/scripts/last30days.py", |
| 166 | "AI agents", |
| 167 | "--discover-shallow", |
| 168 | "--mock", |
| 169 | ], |
| 170 | cwd=REPO_ROOT, |
| 171 | capture_output=True, |
| 172 | text=True, |
| 173 | check=False, |
| 174 | ) |
| 175 | assert result.returncode == 2 |
| 176 | assert "--discover-shallow only applies to --discover runs" in result.stderr |
| 177 | ``` |
| 178 | |
| 179 | The first test asserts not just exit 0 but that the discovery pipeline actually ran (`payload["kind"] == "discovery"`, `payload["domain"] == ""`) - the exact property the truthiness bug would have violated. Source: PR #816 (last30days-skill). |
| 180 | |
| 181 | ## Related |
| 182 | |
| 183 | - [Ranked-output confidence floor + honest empty state](../design-patterns/ranked-output-confidence-floor-honest-empty-state.md) - sibling lesson from the same PR #816 discover rebuild (ranking quality). |
| 184 | - [Non-daemon executor threads defeat wall-clock budgets](../logic-errors/non-daemon-executor-threads-defeat-wall-clock-budget.md) - sibling lesson from PR #816, same lesson class: a discover-mode defect that result-oriented unit tests structurally cannot catch (process lifetime there, bare-flag vs flag-absent conflation here). |
| 185 | - [PR #816](https://github.com/mvanhorn/last30days-skill/pull/816) - the discovery rebuild that introduced the three-state `--discover` flag (released v3.14.0). |
| 186 |