Skip to content
Myr

Temporarily provide a fake context to the callback to hide `UNSET` values as `None`

Before adoption: this commit came in with the history the project adopted, so no landing records it.

authored by Kevin Deldycke · committed by Kevin Deldycke · parent ea70da4 · Browse files · 3 files+143 added−1 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Trailers

  • Fix: https://github.com/pallets/click/issues/3136

Diff stats

3 files+143 added−1 removed

  • tests:+110 added−0 removed
  • other:+33 added−1 removed

3 files+143 added−1 removed

modified:src/click/core.py+31 added-1 removed
2438 unmodified lines
2439 # Legacy case: UNSET is not exposed directly to the callback, but converted2440 # to None.2441 if value is UNSET:2442 value = None2443 value = self.callback(ctx, self, value)24432444 # Search for parameters with UNSET values in the context.2445 unset_keys = {k: None for k, v in ctx.params.items() if v is UNSET}2446 # No UNSET values, call the callback as usual.2447 if not unset_keys:2448 value = self.callback(ctx, self, value)24492450 # Legacy case: provide a temporarily manipulated context to the callback2451 # to hide UNSET values as None.2452 #2453 # Refs:2454 # https://github.com/pallets/click/issues/31362455 # https://github.com/pallets/click/pull/31372456 else:2457 # Add another layer to the context stack to clearly hint that the2458 # context is temporarily modified.2459 with ctx:2460 # Update the context parameters to replace UNSET with None.2461 ctx.params.update(unset_keys)2462 # Feed these fake context parameters to the callback.2463 value = self.callback(ctx, self, value)2464 # Restore the UNSET values in the context parameters.2465 ctx.params.update(2466 {2467 k: UNSET2468 for k in unset_keys2469 # Only restore keys that are present and still None, in case2470 # the callback modified other parameters.2471 if k in ctx.params and ctx.params[k] is None2472 }2473 )24742475 return value24762477 def resolve_envvar_value(self, ctx: Context) -> str | None:2478 """Returns the value found in the environment variable(s) attached to this
937 unmodified lines
modified:tests/test_context.py+110 added
179 unmodified lines
180 pass_value = pass_meta_key("value", doc_description="the test value")181 assert "passes the test value" in pass_value.__doc__182183184def test_hiding_of_unset_sentinel_in_callbacks():185 """Fix: https://github.com/pallets/click/issues/3136"""186187 def inspect_other_params(ctx, param, value):188 """A callback that inspects other parameters' values via the context."""189 assert click.get_current_context() is ctx190 click.echo(f"callback.my_arg: {ctx.params.get('my_arg')!r}")191 click.echo(f"callback.my_opt: {ctx.params.get('my_opt')!r}")192 click.echo(f"callback.my_callback: {ctx.params.get('my_callback')!r}")193194 click.echo(f"callback.param: {param!r}")195 click.echo(f"callback.value: {value!r}")196197 return "hard-coded"198199 class ParameterInternalCheck(Option):200 """An option that checks internal state during processing."""201202 def process_value(self, ctx, value):203 """Check that UNSET values are hidden as None in ctx.params within the204 callback, and then properly restored afterwards.205 """206 assert click.get_current_context() is ctx207 click.echo(f"before_process.my_arg: {ctx.params.get('my_arg')!r}")208 click.echo(f"before_process.my_opt: {ctx.params.get('my_opt')!r}")209 click.echo(f"before_process.my_callback: {ctx.params.get('my_callback')!r}")210211 value = super().process_value(ctx, value)212213 assert click.get_current_context() is ctx214 click.echo(f"after_process.my_arg: {ctx.params.get('my_arg')!r}")215 click.echo(f"after_process.my_opt: {ctx.params.get('my_opt')!r}")216 click.echo(f"after_process.my_callback: {ctx.params.get('my_callback')!r}")217218 return value219220 def change_other_params(ctx, param, value):221 """A callback that modifies other parameters' values via the context."""222 assert click.get_current_context() is ctx223 click.echo(f"before_change.my_arg: {ctx.params.get('my_arg')!r}")224 click.echo(f"before_change.my_opt: {ctx.params.get('my_opt')!r}")225 click.echo(f"before_change.my_callback: {ctx.params.get('my_callback')!r}")226227 click.echo(f"before_change.param: {param!r}")228 click.echo(f"before_change.value: {value!r}")229230 ctx.params["my_arg"] = "changed"231 # Reset to None parameters that where not UNSET to see they are not forced back232 # to UNSET.233 ctx.params["my_callback"] = None234235 return value236237 @click.command238 @click.argument("my-arg", required=False)239 @click.option("--my-opt")240 @click.option("--my-callback", callback=inspect_other_params)241 @click.option("--check-internal", cls=ParameterInternalCheck)242 @click.option(243 "--modifying-callback", cls=ParameterInternalCheck, callback=change_other_params244 )245 @click.pass_context246 def cli(ctx, my_arg, my_opt, my_callback, check_internal, modifying_callback):247 click.echo(f"cli.my_arg: {my_arg!r}")248 click.echo(f"cli.my_opt: {my_opt!r}")249 click.echo(f"cli.my_callback: {my_callback!r}")250 click.echo(f"cli.check_internal: {check_internal!r}")251 click.echo(f"cli.modifying_callback: {modifying_callback!r}")252253 runner = click.testing.CliRunner()254 result = runner.invoke(cli)255256 assert result.stdout.splitlines() == [257 # Values of other parameters within the callback are None, not UNSET.258 "callback.my_arg: None",259 "callback.my_opt: None",260 "callback.my_callback: None",261 "callback.param: <Option my_callback>",262 "callback.value: None",263 # Previous UNSET values were not altered by the callback.264 "before_process.my_arg: Sentinel.UNSET",265 "before_process.my_opt: Sentinel.UNSET",266 "before_process.my_callback: 'hard-coded'",267 "after_process.my_arg: Sentinel.UNSET",268 "after_process.my_opt: Sentinel.UNSET",269 "after_process.my_callback: 'hard-coded'",270 # Changes on other parameters within the callback are restored afterwards.271 "before_process.my_arg: Sentinel.UNSET",272 "before_process.my_opt: Sentinel.UNSET",273 "before_process.my_callback: 'hard-coded'",274 "before_change.my_arg: None",275 "before_change.my_opt: None",276 "before_change.my_callback: 'hard-coded'",277 "before_change.param: <ParameterInternalCheck modifying_callback>",278 "before_change.value: None",279 "after_process.my_arg: 'changed'",280 "after_process.my_opt: Sentinel.UNSET",281 "after_process.my_callback: None",282 # Unset values within the main command are UNSET, but hidden as None.283 "cli.my_arg: 'changed'",284 "cli.my_opt: None",285 "cli.my_callback: None",286 "cli.check_internal: None",287 "cli.modifying_callback: None",288 ]289 assert not result.stderr290 assert not result.exception291 assert result.exit_code == 0292293294def test_context_pushing():295 rv = []296297 @click.command()
485 unmodified lines
modified:CHANGES.rst+2 added
9 unmodified lines
10- Replace ``Sentinel.UNSET`` default values by ``None`` as they're passed through11 the ``Context.invoke()`` method. :issue:`3066` :issue:`3065` :pr:`3068`12- Fix conversion of ``Sentinel.UNSET`` happening too early, which caused incorrect13 behavior for multiple parameters using the same name. :issue:`3071` :pr:`3079`14- Hide ``Sentinel.UNSET`` values as ``None`` when looking up for other parameters15 through the context inside parameter callbacks. :issue:`3136` :pr:`3137`16- Fix rendering when ``prompt`` and ``confirm`` parameter ``prompt_suffix`` is17 empty. :issue:`3019` :pr:`3021`18- When ``Sentinel.UNSET`` is found during parsing, it will skip calls to19 ``type_cast_value``. :issue:`3069` :pr:`3090`
1291 unmodified lines