Fix callable ``flag_value`` being instantiated when used as a default
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Closes #3121 Refs: #3201 #3213
authored by Kevin Deldycke · committed by Kevin Deldycke · parent ae46cfd · 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
Provenance
- Commit
546f285- Tree
9f4fdb2- Author
Kevin Deldycke <kevin@deldycke.com>- Committer
Kevin Deldycke <kevin@deldycke.com>- Parent
ae46cfd
4 files changed+234 added−9 removed
modified:src/click/core.py+20 added-6 removed
2817 unmodified lines2818 if self.is_bool_flag:2819 if self.default is UNSET and not self.required:2820 self.default = False2821 2822- # 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_value2828 2829 # Set the default flag_value if it is not set.2830 if self.flag_value is UNSET:2831 if self.is_flag:55 unmodified lines2887 hidden=self.hidden,2888 )2889 return info_dict2890 2891+ 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)2895+2896+ # 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()2904+2905+ return value2906+2907 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 linesmodified:tests/test_defaults.py+45 added
1 import pytest2 3 import click4+from click import UNPROCESSED5 6 7 @pytest.mark.parametrize(8 ("default", "type", "expected_output", "expected_type"),300 unmodified lines309 # 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.output313+314+315+class _Marker:316+ """Dummy callable used as a flag_value in default tests."""317+318+ pass319+320+321+@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+)338+def 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.341+342+ Verifies the fix for https://github.com/pallets/click/issues/3121 does not343+ break ``default_map`` precedence.344+ """345+346+ @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)350+351+ 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 lines289 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 lines2160 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 lines2183 # 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 lines2269 else:2270 assert result.output == repr(expected)2271 2272 2273+@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+)2310+def 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+ """2315+2316+ @click.command()2317+ @click.option("--opt", "value", **opt_params)2318+ def cli(value):2319+ click.echo(repr(value), nl=False)2320+2321+ 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)2327+2328+2329+def test_callable_flag_value_default_map(runner):2330+ """A ``default_map`` entry should override the auto-aligned callable ``flag_value``.2331+2332+ 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+ """2337+2338+ @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)2342+2343+ # 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")2346+2347+ # 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")2350+2351+ # CLI arg still wins over everything.2352+ result = runner.invoke(cli, ["--opt"])2353+ assert result.output == repr(Class1)2354+2355+2356+def test_callable_flag_value_show_default(runner):2357+ """Help text with ``show_default=True`` should display the class name, not2358+ instantiate it.2359+ """2360+2361+ @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+ pass2372+2373+ result = runner.invoke(cli, ["--help"])2374+ assert result.exit_code == 02375+ assert "Class1" in result.output2376+ assert "object at 0x" not in result.output2377+2378+2379+@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+)2409+def 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``.2416+2417+ A user subclass that reads ``self.default`` directly (bypassing2418+ ``get_default()``) will see ``True`` instead of the ``flag_value``.2419+ """2420+2421+ @click.command()2422+ @click.option("--opt", "value", **opt_params)2423+ def cli(value):2424+ pass2425+2426+ opt = cli.params[0]2427+2428+ # The raw attribute reflects what the user wrote.2429+ assert opt.default is expected_default_attr2430+2431+ # get_default() resolves the alignment lazily.2432+ ctx = click.Context(cli)2433+ assert opt.get_default(ctx, call=True) is expected_get_default2434+2435+2436 def test_custom_type_frozenset_flag_value(runner):2437 """Check that frozenset is correctly handled as a type, a flag value and a default.2438 2439 Reproduces https://github.com/pallets/click/issues/261064 unmodified linesmodified:CHANGES.rst+2 added
10 unmodified lines11 - 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`17 18 Version 8.3.119 --------------20 1305 unmodified lines