Auto-detect `type=UNPROCESSED` when `flag_value` has non-basic types (#3363)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by Rowlando13 · committed by GitHub · parents c8da1fc, cf93868 · Browse files · 3 files·+113 added−19 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
3 files+113 added−19 removed
- tests:+66 added−17 removed
- other:+47 added−2 removed
Provenance
- Commit
b03f211- Tree
fae0e17- Author
Rowlando13 <67291205+Rowlando13@users.noreply.github.com>- Committer
GitHub <noreply@github.com>- Parent 1
c8da1fc- Parent 2
cf93868
3 files changed+113 added−19 removed
modified:src/click/core.py+21 added-2 removed
2717 unmodified lines2718 :param help: the help string.2719 :param hidden: hide this option from help outputs.2720 :param attrs: Other command arguments described in :class:`Parameter`.2721 2722+ .. versionchanged:: 8.42723+ Non-basic ``flag_value`` types (not ``str``, ``int``, ``float``, or2724+ ``bool``) are passed through unchanged instead of being stringified.2725+ Previously, ``type=click.UNPROCESSED`` was required to preserve them.2726+2727 .. versionchanged:: 8.22728 ``envvar`` used with ``flag_value`` will always use the ``flag_value``,2729 previously it would use the value of the environment variable.2730 9 unmodified lines2740 The default of a single option boolean flag is not shown if the2741 default value is ``False``.2742 2743 .. versionchanged:: 8.0.12739- ``type`` is detected from ``flag_value`` if given.2744+ ``type`` is detected from ``flag_value`` if given, for basic Python2745+ types (``str``, ``int``, ``float``, ``bool``).2746 """2747 2748 param_type_name = "option"2749 91 unmodified lines2841 elif isinstance(flag_value, bool):2842 self.type = types.BoolParamType()2843 # Otherwise, guess the type from the flag value.2844 else:2839- self.type = types.convert_type(None, flag_value)2845+ guessed = types.convert_type(None, flag_value)2846+ if (2847+ isinstance(guessed, types.StringParamType)2848+ and not isinstance(flag_value, str)2849+ and flag_value is not None2850+ ):2851+ # The flag_value type couldn't be auto-detected2852+ # (not str, int, float, or bool). Since flag_value2853+ # is a programmer-provided Python object, not CLI2854+ # input, pass it through unchanged instead of2855+ # stringifying it.2856+ self.type = types.UNPROCESSED2857+ else:2858+ self.type = guessed2859 2860 self.is_flag: bool = bool(is_flag)2861 self.is_bool_flag: bool = bool(2862 is_flag and isinstance(self.type, types.BoolParamType)638 unmodified linesmodified:tests/test_options.py+66 added-17 removed
1404 unmodified lines1405 param = click.Option(["-a", "x"], default=True, flag_value=4)1406 assert param.type is click.INT1407 param = click.Option(["-b", "x"], flag_value=8)1408 assert param.type is click.INT1409+ # Non-basic types auto-detect as UNPROCESSED to avoid stringification.1410+ param = click.Option(["-c", "x"], flag_value=EngineType.OSS)1411+ assert param.type is click.UNPROCESSED1412+ param = click.Option(["-d", "x"], flag_value=frozenset())1413+ assert param.type is click.UNPROCESSED1414 1415 1416 @pytest.mark.parametrize(1417 ("opt_params", "args", "expected"),713 unmodified lines2131 {"type": EngineType, "flag_value": EngineType.OSS, "default": True},2132 [],2133 EngineType.OSS,2134 ),2130- # Type is not specified and default to string, so the default value is2131- # returned as a string, even if it is a boolean. Also, defaults to the2132- # flag_value instead of the default value to support legacy behavior.2135+ # Type is not specified. For string flag_value, STRING type is used and2136+ # the default value is converted to string. For non-basic types (like2137+ # enums), UNPROCESSED is used and values pass through unchanged.2138 ({"flag_value": "1", "default": True}, [], "1"),2139 ({"flag_value": "1", "default": 42}, [], "42"),2135- ({"flag_value": EngineType.OSS, "default": True}, [], "EngineType.OSS"),2136- ({"flag_value": EngineType.OSS, "default": 42}, [], "42"),2140+ ({"flag_value": EngineType.OSS, "default": True}, [], EngineType.OSS),2141+ ({"flag_value": EngineType.OSS, "default": 42}, [], 42),2142 # See: the result is the same if we force the type to be str.2143 ({"type": str, "flag_value": 1, "default": True}, [], "1"),2144 ({"type": str, "flag_value": 1, "default": 42}, [], "42"),2145 ({"type": str, "flag_value": "1", "default": True}, [], "1"),57 unmodified lines2203 {"flag_value": EngineType.PRO, "type": UNPROCESSED},2204 ["--opt2"],2205 EngineType.PRO,2206 ),2202- # Check that passing exotic flag values like classes is supported, but are2203- # rendered to strings when the type is not specified.2207+ # Exotic flag values like classes are passed through unchanged when no2208+ # explicit type is given (UNPROCESSED is auto-detected).2209+ # https://github.com/pallets/click/issues/20122210 # https://github.com/pallets/click/issues/31212211 (2212 {"flag_value": Class1, "default": True},2213 {"flag_value": Class2},2214 [],2209- "<class 'test_options.Class1'>",2215+ Class1,2216 ),2217 (2218 {"flag_value": Class1, "default": True},2219 {"flag_value": Class2},2220 ["--opt1"],2215- "<class 'test_options.Class1'>",2221+ Class1,2222 ),2223 (2224 {"flag_value": Class1, "default": True},2225 {"flag_value": Class2},2226 ["--opt2"],2221- "<class 'test_options.Class2'>",2227+ Class2,2228 ),2223- # Even the default is processed as a string.2229+ # String and None defaults pass through unchanged.2230 ({"flag_value": Class1, "default": "True"}, {"flag_value": Class2}, [], "True"),2231 ({"flag_value": Class1, "default": None}, {"flag_value": Class2}, [], None),2232 # To get the classes as-is, we need to specify the type as UNPROCESSED.2233 # https://github.com/pallets/click/issues/312116 unmodified lines2250 Class2,2251 ),2252 # Setting the default to a class, an instance of the class is returned instead2253 # of the class itself, because the default is allowed to be callable (and2248- # consummd). And this happens whatever the type is.2254+ # consumed). And this happens whatever the type is.2255 (2256 {"flag_value": Class1, "default": Class1},2257 {"flag_value": Class2},2258 [],2253- re.compile(r"'<test_options.Class1 object at 0x[0-9A-Fa-f]+>'"),2259+ re.compile(r"<test_options.Class1 object at 0x[0-9A-Fa-f]+>"),2260 ),2261 (2262 {"flag_value": Class1, "default": Class2},2263 {"flag_value": Class2},2264 [],2259- re.compile(r"'<test_options.Class2 object at 0x[0-9A-Fa-f]+>'"),2265+ re.compile(r"<test_options.Class2 object at 0x[0-9A-Fa-f]+>"),2266 ),2267 (2268 {"flag_value": Class1, "type": UNPROCESSED, "default": Class1},2269 {"flag_value": Class2, "type": UNPROCESSED},57 unmodified lines2327 {"flag_value": Class1, "type": UNPROCESSED, "default": True},2328 ["--opt"],2329 Class1,2330 ),2325- # Without UNPROCESSED, the class is str()-ified by the default STRING type.2326- ({"flag_value": Class1, "default": True}, [], "<class 'test_options.Class1'>"),2331+ # Without explicit UNPROCESSED, the class still passes through unchanged2332+ # because UNPROCESSED is auto-detected for non-basic flag_value types.2333+ ({"flag_value": Class1, "default": True}, [], Class1),2334 (2335 {"flag_value": Class1, "default": True},2336 ["--opt"],2330- "<class 'test_options.Class1'>",2337+ Class1,2338 ),2339 # Explicit default=Class1 (not via default=True alignment): callable IS invoked,2340 # because the user explicitly set a callable as the default.2341 (137 unmodified lines2479 ctx = click.Context(cli)2480 assert opt.get_default(ctx, call=True) is expected_get_default2481 2482 2483+def test_flag_value_not_stringified_for_custom_types(runner):2484+ """Non-basic flag_value types are passed through unchanged without2485+ requiring ``type=click.UNPROCESSED``.2486+2487+ Regression test for https://github.com/pallets/click/issues/20122488+ """2489+2490+ @click.command()2491+ @click.option("--cls1", "config_cls", flag_value=Class1, default=True)2492+ @click.option("--cls2", "config_cls", flag_value=Class2)2493+ def cli(config_cls):2494+ click.echo(repr(config_cls), nl=False)2495+2496+ # Default activates --cls1 (default=True resolves to flag_value).2497+ result = runner.invoke(cli, [])2498+ assert result.exit_code == 02499+ assert result.output == repr(Class1)2500+2501+ result = runner.invoke(cli, ["--cls1"])2502+ assert result.exit_code == 02503+ assert result.output == repr(Class1)2504+2505+ result = runner.invoke(cli, ["--cls2"])2506+ assert result.exit_code == 02507+ assert result.output == repr(Class2)2508+2509+ # Enum flag_value without explicit type is also preserved.2510+ @click.command()2511+ @click.option("--oss", "engine", flag_value=EngineType.OSS, default=True)2512+ @click.option("--pro", "engine", flag_value=EngineType.PRO)2513+ def cli2(engine):2514+ click.echo(repr(engine), nl=False)2515+2516+ result = runner.invoke(cli2, [])2517+ assert result.exit_code == 02518+ assert result.output == repr(EngineType.OSS)2519+2520+ result = runner.invoke(cli2, ["--pro"])2521+ assert result.exit_code == 02522+ assert result.output == repr(EngineType.PRO)2523+2524+2525 def test_custom_type_frozenset_flag_value(runner):2526 """Check that frozenset is correctly handled as a type, a flag value and a default.2527 2528 Reproduces https://github.com/pallets/click/issues/261096 unmodified linesmodified:CHANGES.rst+26 added
18 unmodified lines19 generic with abstract methods.20 - Split string values from ``default_map`` for parameters with ``nargs > 1``21 or :class:`Tuple` type, matching environment variable behavior.22 :issue:`2745` :pr:`3364`23+- Auto-detect ``type=UNPROCESSED`` for ``flag_value`` of non-basic types24+ (not ``str``, ``int``, ``float``, or ``bool``), so programmer-provided25+ Python objects like classes and enum members are passed through unchanged26+ instead of being stringified. Previously ``type=click.UNPROCESSED`` had27+ to be set explicitly. :issue:`2012` :pr:`3363`28 29 Version 8.3.330 -------------31 32+Unreleased33+34+- :class:`ParamType` typing improvements. :pr:`3371`35+36+ - :class:`ParamType` is now a generic abstract base class,37+ parameterized by its converted value type.38+ - :meth:`~ParamType.convert` return types are narrowed on all39+ concrete types (``str`` for :class:`STRING`, ``int`` for40+ :class:`INT`, etc.).41+ - :meth:`~ParamType.to_info_dict` returns specific42+ :class:`~typing.TypedDict` subclasses instead of43+ ``dict[str, Any]``.44+ - :class:`CompositeParamType` and the number-range base are now45+ generic with abstract methods.46+- Split string values from ``default_map`` for parameters with ``nargs > 1``47+ or :class:`Tuple` type, matching environment variable behavior.48+ :issue:`2745` :pr:`3364`49+50+Version 8.3.351+-------------52+53 Released 2026-04-2054 55 - Use :func:`shlex.split` to split pager and editor commands into ``argv``56 lists for :class:`subprocess.Popen`, removing ``shell=True``.1360 unmodified lines