Auto-detect `type=UNPROCESSED` when `flag_value` has non-basic types
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Closes #2012
authored by Kevin Deldycke · committed by Kevin Deldycke · parent f1f191e · Browse files · 3 files·+92 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+92 added−19 removed
- tests:+66 added−17 removed
- other:+26 added−2 removed
Provenance
- Commit
4e4c7a6- Tree
868489d- Author
Kevin Deldycke <kevin@deldycke.com>- Committer
Kevin Deldycke <kevin@deldycke.com>- Parent
f1f191e
3 files changed+92 added−19 removed
modified:src/click/core.py+21 added-2 removed
2712 unmodified lines2713 :param help: the help string.2714 :param hidden: hide this option from help outputs.2715 :param attrs: Other command arguments described in :class:`Parameter`.2716 2717+ .. versionchanged:: 8.42718+ Non-basic ``flag_value`` types (not ``str``, ``int``, ``float``, or2719+ ``bool``) are passed through unchanged instead of being stringified.2720+ Previously, ``type=click.UNPROCESSED`` was required to preserve them.2721+2722 .. versionchanged:: 8.22723 ``envvar`` used with ``flag_value`` will always use the ``flag_value``,2724 previously it would use the value of the environment variable.2725 9 unmodified lines2735 The default of a single option boolean flag is not shown if the2736 default value is ``False``.2737 2738 .. versionchanged:: 8.0.12734- ``type`` is detected from ``flag_value`` if given.2739+ ``type`` is detected from ``flag_value`` if given, for basic Python2740+ types (``str``, ``int``, ``float``, ``bool``).2741 """2742 2743 param_type_name = "option"2744 91 unmodified lines2836 elif isinstance(flag_value, bool):2837 self.type = types.BoolParamType()2838 # Otherwise, guess the type from the flag value.2839 else:2834- self.type = types.convert_type(None, flag_value)2840+ guessed = types.convert_type(None, flag_value)2841+ if (2842+ isinstance(guessed, types.StringParamType)2843+ and not isinstance(flag_value, str)2844+ and flag_value is not None2845+ ):2846+ # The flag_value type couldn't be auto-detected2847+ # (not str, int, float, or bool). Since flag_value2848+ # is a programmer-provided Python object, not CLI2849+ # input, pass it through unchanged instead of2850+ # stringifying it.2851+ self.type = types.UNPROCESSED2852+ else:2853+ self.type = guessed2854 2855 self.is_flag: bool = bool(is_flag)2856 self.is_bool_flag: bool = bool(2857 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+5 added
38 unmodified lines39 :issue:`2865`40 - Change :class:`ParameterSource` to an :class:`~enum.IntEnum` and reorder41 its members from most to least explicit, so values can be compared to42 check whether a parameter was explicitly provided. :issue:`2879` :pr:`3248`43+- Auto-detect ``type=UNPROCESSED`` for ``flag_value`` of non-basic types44+ (not ``str``, ``int``, ``float``, or ``bool``), so programmer-provided45+ Python objects like classes and enum members are passed through unchanged46+ instead of being stringified. Previously ``type=click.UNPROCESSED`` had47+ to be set explicitly. :issue:`2012` :pr:`3363`48 49 Version 8.3.250 -------------51 1323 unmodified lines