Skip to content
Myr

Fix callable ``flag_value`` being instantiated when used as a default (#3225)

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

authored by Rowlando13 · committed by GitHub · parents ae46cfd, 546f285 · Browse files · 4 files+234 added−9 removed
This commit

State

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

Diff stats

4 files+234 added−9 removed

  • tests:+212 added−3 removed
  • other:+22 added−6 removed

4 files+234 added−9 removed

modified:src/click/core.py+20 added-6 removed
2817 unmodified lines
2818 if self.is_bool_flag:2819 if self.default is UNSET and not self.required:2820 self.default = False28212822 # Support the special case of aligning the default value with the flag_value2823 # for flags whose default is explicitly set to True. Note that as long as we2824 # have this condition, there is no way a flag can have a default set to True,2825 # and a flag_value set to something else. Refs:2822 # The alignement of default to the flag_value is resolved lazily in2823 # get_default() to prevent callable flag_values (like classes) from2824 # being instantiated. Refs:2825 # https://github.com/pallets/click/issues/31212826 # https://github.com/pallets/click/issues/3024#issuecomment-31461994612827 # https://github.com/pallets/click/pull/3030/commits/06847da2828 if self.default is True and self.flag_value is not UNSET:2829 self.default = self.flag_value28282829 # Set the default flag_value if it is not set.2830 if self.flag_value is UNSET:2831 if self.is_flag:
55 unmodified lines
2887 hidden=self.hidden,2888 )2889 return info_dict28902891 def get_default(2892 self, ctx: Context, call: bool = True2893 ) -> t.Any | t.Callable[[], t.Any] | None:2894 value = super().get_default(ctx, call=False)28952896 # Lazily resolve default=True to flag_value. Doing this here2897 # (instead of eagerly in __init__) prevents callable flag_values2898 # (like classes) from being instantiated by the callable check below.2899 # https://github.com/pallets/click/issues/31212900 if value is True and self.is_flag:2901 value = self.flag_value2902 elif call and callable(value):2903 value = value()29042905 return value29062907 def get_error_hint(self, ctx: Context) -> str:2908 result = super().get_error_hint(ctx)2909 if self.show_envvar and self.envvar is not None:2910 result += f" (env var: '{self.envvar}')"
527 unmodified lines
modified:tests/test_defaults.py+45 added
1import pytest23import click4from click import UNPROCESSED567@pytest.mark.parametrize(8 ("default", "type", "expected_output", "expected_type"),
300 unmodified lines
309 # rendering --help with show_default=True.310 result = runner.invoke(cli, ["--help"], default_map=default_map)311 assert not result.exception312 assert "prefix@example.com" in result.output313314315class _Marker:316 """Dummy callable used as a flag_value in default tests."""317318 pass319320321@pytest.mark.parametrize(322 ("default_map", "args", "expected"),323 [324 # No default_map: auto-aligned default returns the class, not an instance.325 (None, [], _Marker),326 # CLI flag always returns the class.327 (None, ["--opt"], _Marker),328 # Static value in default_map overrides the auto-aligned flag_value.329 ({"value": "from-map"}, [], "from-map"),330 # Callable in default_map is still invoked (not suppressed by the fix).331 ({"value": lambda: "lazy-map"}, [], "lazy-map"),332 # None in default_map overrides the flag_value.333 ({"value": None}, [], None),334 # CLI arg wins over default_map.335 ({"value": "from-map"}, ["--opt"], _Marker),336 ],337)338def test_default_map_with_callable_flag_value(runner, default_map, args, expected):339 """``default_map`` entries should override the auto-aligned callable ``flag_value``,340 and callable entries in ``default_map`` should still be invoked.341342 Verifies the fix for https://github.com/pallets/click/issues/3121 does not343 break ``default_map`` precedence.344 """345346 @click.command()347 @click.option("--opt", "value", flag_value=_Marker, type=UNPROCESSED, default=True)348 def cli(value):349 click.echo(repr(value), nl=False)350351 kwargs = {}352 if default_map is not None:353 kwargs["default_map"] = default_map354 result = runner.invoke(cli, args, **kwargs)355 assert result.exit_code == 0356 assert result.output == repr(expected)
modified:tests/test_options.py+167 added-3 removed
288 unmodified lines
289 7.9,290 None,291 "Error: Invalid value for '-a': Value must be an iterable.",292 ),293 #293 (294 False,295 2,296 42,
1863 unmodified lines
2160 EngineType.PRO,2161 ),2162 # Check that passing exotic flag values like classes is supported, but are2163 # rendered to strings when the type is not specified.2164 # https://github.com/pallets/click/issues/31212165 (2166 {"flag_value": Class1, "default": True},2167 {"flag_value": Class2},2168 [],2169 re.compile(r"'<test_options.Class1 object at 0x[0-9A-Fa-f]+>'"),2169 "<class 'test_options.Class1'>",2170 ),2171 (2172 {"flag_value": Class1, "default": True},2173 {"flag_value": Class2},
9 unmodified lines
2183 # Even the default is processed as a string.2184 ({"flag_value": Class1, "default": "True"}, {"flag_value": Class2}, [], "True"),2185 ({"flag_value": Class1, "default": None}, {"flag_value": Class2}, [], None),2186 # To get the classes as-is, we need to specify the type as UNPROCESSED.2187 # https://github.com/pallets/click/issues/31212188 (2189 {"flag_value": Class1, "type": UNPROCESSED, "default": True},2190 {"flag_value": Class2, "type": UNPROCESSED},2191 [],2191 re.compile(r"<test_options.Class1 object at 0x[0-9A-Fa-f]+>"),2192 Class1,2193 ),2194 (2195 {"flag_value": Class1, "type": UNPROCESSED, "default": True},2196 {"flag_value": Class2, "type": UNPROCESSED},
72 unmodified lines
2269 else:2270 assert result.output == repr(expected)227122722273@pytest.mark.parametrize(2274 ("opt_params", "args", "expected"),2275 [2276 # Class flag_value with default=True and UNPROCESSED: the class itself is2277 # returned, NOT an instance. Regression test for2278 # https://github.com/pallets/click/issues/31212279 ({"flag_value": Class1, "type": UNPROCESSED, "default": True}, [], Class1),2280 (2281 {"flag_value": Class1, "type": UNPROCESSED, "default": True},2282 ["--opt"],2283 Class1,2284 ),2285 # Without UNPROCESSED, the class is str()-ified by the default STRING type.2286 ({"flag_value": Class1, "default": True}, [], "<class 'test_options.Class1'>"),2287 (2288 {"flag_value": Class1, "default": True},2289 ["--opt"],2290 "<class 'test_options.Class1'>",2291 ),2292 # Explicit default=Class1 (not via default=True alignment): callable IS invoked,2293 # because the user explicitly set a callable as the default.2294 (2295 {"flag_value": Class1, "type": UNPROCESSED, "default": Class1},2296 [],2297 re.compile(r"<test_options.Class1 object at 0x[0-9A-Fa-f]+>"),2298 ),2299 # Explicit default=Class2, different from flag_value=Class1.2300 (2301 {"flag_value": Class1, "type": UNPROCESSED, "default": Class2},2302 [],2303 re.compile(r"<test_options.Class2 object at 0x[0-9A-Fa-f]+>"),2304 ),2305 # Non-callable flag_value with default=True: unaffected by the fix.2306 ({"flag_value": "upper", "default": True}, [], "upper"),2307 ({"flag_value": "upper", "default": True}, ["--opt"], "upper"),2308 ],2309)2310def test_callable_flag_value_not_instantiated(runner, opt_params, args, expected):2311 """A callable ``flag_value`` like a class, with ``default=True`` should not be2312 invoked when resolving the default. This is the single-option variant of2313 the regression reported in https://github.com/pallets/click/issues/3121.2314 """23152316 @click.command()2317 @click.option("--opt", "value", **opt_params)2318 def cli(value):2319 click.echo(repr(value), nl=False)23202321 result = runner.invoke(cli, args)2322 assert result.exit_code == 02323 if isinstance(expected, re.Pattern):2324 assert re.match(expected, result.output)2325 else:2326 assert result.output == repr(expected)232723282329def test_callable_flag_value_default_map(runner):2330 """A ``default_map`` entry should override the auto-aligned callable ``flag_value``.23312332 When ``default=True`` and ``flag_value=SomeClass``, the default is aligned to2333 ``SomeClass``. If ``default_map`` provides a different value (including a2334 callable), it should take precedence and callables from ``default_map`` should2335 still be invoked.2336 """23372338 @click.command()2339 @click.option("--opt", "value", flag_value=Class1, type=UNPROCESSED, default=True)2340 def cli(value):2341 click.echo(repr(value), nl=False)23422343 # Static value in default_map overrides the flag_value default.2344 result = runner.invoke(cli, [], default_map={"value": "from-map"})2345 assert result.output == repr("from-map")23462347 # Callable in default_map is still invoked (not suppressed by the fix).2348 result = runner.invoke(cli, [], default_map={"value": lambda: "lazy-map"})2349 assert result.output == repr("lazy-map")23502351 # CLI arg still wins over everything.2352 result = runner.invoke(cli, ["--opt"])2353 assert result.output == repr(Class1)235423552356def test_callable_flag_value_show_default(runner):2357 """Help text with ``show_default=True`` should display the class name, not2358 instantiate it.2359 """23602361 @click.command()2362 @click.option(2363 "--opt",2364 "value",2365 flag_value=Class1,2366 type=UNPROCESSED,2367 default=True,2368 show_default=True,2369 )2370 def cli(value):2371 pass23722373 result = runner.invoke(cli, ["--help"])2374 assert result.exit_code == 02375 assert "Class1" in result.output2376 assert "object at 0x" not in result.output237723782379@pytest.mark.parametrize(2380 ("opt_params", "expected_default_attr", "expected_get_default"),2381 [2382 # default=True with callable flag_value: the attribute stays True2383 # (not eagerly aligned), but get_default() resolves to the flag_value.2384 (2385 {"flag_value": Class1, "type": UNPROCESSED, "default": True},2386 True,2387 Class1,2388 ),2389 # default=True with non-callable flag_value: same lazy resolution.2390 (2391 {"flag_value": "upper", "default": True},2392 True,2393 "upper",2394 ),2395 # Explicit default (not True): attribute and get_default() agree.2396 (2397 {"flag_value": Class1, "type": UNPROCESSED, "default": "custom"},2398 "custom",2399 "custom",2400 ),2401 # No default: attribute and get_default() are both UNSET.2402 (2403 {"flag_value": Class1, "type": UNPROCESSED},2404 UNSET,2405 UNSET,2406 ),2407 ],2408)2409def test_callable_flag_value_get_default_override(2410 runner, opt_params, expected_default_attr, expected_get_default2411):2412 """The ``default=True`` to ``flag_value`` alignment is resolved lazily in2413 ``get_default()`` rather than eagerly in ``__init__``. This means2414 ``option.default`` stays as ``True`` while ``get_default()`` returns the2415 ``flag_value``.24162417 A user subclass that reads ``self.default`` directly (bypassing2418 ``get_default()``) will see ``True`` instead of the ``flag_value``.2419 """24202421 @click.command()2422 @click.option("--opt", "value", **opt_params)2423 def cli(value):2424 pass24252426 opt = cli.params[0]24272428 # The raw attribute reflects what the user wrote.2429 assert opt.default is expected_default_attr24302431 # get_default() resolves the alignment lazily.2432 ctx = click.Context(cli)2433 assert opt.get_default(ctx, call=True) is expected_get_default243424352436def test_custom_type_frozenset_flag_value(runner):2437 """Check that frozenset is correctly handled as a type, a flag value and a default.24382439 Reproduces https://github.com/pallets/click/issues/2610
64 unmodified lines
modified:CHANGES.rst+2 added
10 unmodified lines
11- Add comprehensive tests for ``CliRunner`` stream lifecycle, covering12 logging interaction, multi-threaded safety, and sequential invocation13 isolation. Add high-iteration stress tests behind a ``stress`` marker14 with a dedicated CI job. :pr:`3139`15- Fix callable ``flag_value`` being instantiated when used as a default via16 ``default=True``. :issue:`3121` :pr:`3201` :pr:`3213` :pr:`3225`1718Version 8.3.119--------------20
1305 unmodified lines