Skip to content
Myr

refactor int, float, and range types with common bases

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

allow specifying min and max as open separately clamp works for open int bounds, fails for open float bounds help output shows range information

authored by David Lord · committed by David Lord · parent 75b708a · Browse files · 7 files+209 added−231 removed
This commit

State

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

Diff stats

7 files+209 added−231 removed

  • tests:+71 added−100 removed
  • other:+138 added−131 removed

7 files+209 added−231 removed

modified:docs/options.rst+16 added-21 removed
773 unmodified lines
774775Range Options776-------------777778A special mention should go to the :class:`IntRange` type, which works very779similarly to the :data:`INT` type, but restricts the value to fall into a780specific range (inclusive on both edges). It has two modes:778The :class:`IntRange` type extends the :data:`INT` type to ensure the779value is contained in the given range. The :class:`FloatRange` type does780the same for :data:`FLOAT`.781782- the default mode (non-clamping mode) where a value that falls outside783 of the range will cause an error.784- an optional clamping mode where a value that falls outside of the785 range will be clamped. This means that a range of ``0-5`` would786 return ``5`` for the value ``10`` or ``0`` for the value ``-1`` (for787 example).782If ``min`` or ``max`` is omitted, that side is *unbounded*. Any value in783that direction is accepted. By default, both bounds are *closed*, which784means the boundary value is included in the accepted range. ``min_open``785and ``max_open`` can be used to exclude that boundary from the range.786789Example:787If ``clamp`` mode is enabled, a value that is outside the range is set788to the boundary instead of failing. For example, the range ``0, 5``789would return ``5`` for the value ``10``, or ``0`` for the value ``-1``.790When using :class:`FloatRange`, ``clamp`` can only be enabled if both791bounds are *closed* (the default).792793.. click:example::794795 @click.command()794 @click.option('--count', type=click.IntRange(0, 20, clamp=True))795 @click.option('--digit', type=click.IntRange(0, 10))796 @click.option("--count", type=click.IntRange(0, 20, clamp=True))797 @click.option("--digit", type=click.IntRange(0, 9))798 def repeat(count, digit):799 click.echo(str(digit) * count)800799 if __name__ == '__main__':800 repeat()801802And from the command line:803801.. click:run::802806 invoke(repeat, args=['--count=1000', '--digit=5'])807 invoke(repeat, args=['--count=1000', '--digit=12'])803 invoke(repeat, args=['--count=100', '--digit=5'])804 invoke(repeat, args=['--count=6', '--digit=12'])805809If you pass ``None`` for any of the edges, it means that the range is open810at that side.806807Callbacks for Validation808------------------------809
38 unmodified lines
modified:src/click/core.py+6 added-3 removed
21 unmodified lines
22from .parser import split_opt23from .termui import confirm24from .termui import prompt25from .termui import style26from .types import _NumberRangeBase27from .types import BOOL28from .types import convert_type29from .types import IntRange30from .utils import _detect_program_name
2029 unmodified lines
2060 else:2061 default_string = self.default2062 extra.append(f"default: {default_string}")20632063 if isinstance(self.type, IntRange):2064 if self.type.min is not None and self.type.max is not None:2065 extra.append(f"{self.type.min}-{self.type.max} inclusive")2064 if isinstance(self.type, _NumberRangeBase):2065 range_str = self.type._describe_range()20662067 if range_str:2068 extra.append(range_str)20692070 if self.required:2071 extra.append("required")2072 if extra:2073 extra_str = ";".join(extra)
133 unmodified lines
modified:src/click/types.py+111 added-104 removed
1import os2import operator2import stat3from datetime import datetime45from ._compat import _get_argv_encoding
248 unmodified lines
254 def __repr__(self):255 return "DateTime"256257259class IntParamType(ParamType):260 name = "integer"258class _NumberParamTypeBase(ParamType):259 _number_class = None260261 def convert(self, value, param, ctx):262 try:264 return int(value)263 return self._number_class(value)264 except ValueError:266 self.fail(f"{value} is not a valid integer", param, ctx)265 self.fail(f"{value} is not a valid {self.name}", param, ctx)266268 def __repr__(self):269 return "INT"267271272class IntRange(IntParamType):273 """A parameter that works similar to :data:`click.INT` but restricts274 the value to fit into a range. The default behavior is to fail if the275 value falls outside the range, but it can also be silently clamped276 between the two edges.277278 See :ref:`ranges` for an example.279 """280281 name = "integer range"282283 def __init__(self, min=None, max=None, clamp=False):268class _NumberRangeBase(_NumberParamTypeBase):269 def __init__(self, min=None, max=None, min_open=False, max_open=False, clamp=False):270 self.min = min271 self.max = max272 self.min_open = min_open273 self.max_open = max_open274 self.clamp = clamp275276 def convert(self, value, param, ctx):277 import operator278279 rv = super().convert(value, param, ctx)280 lt_min = self.min is not None and (281 operator.le if self.min_open else operator.lt282 )(rv, self.min)283 gt_max = self.max is not None and (284 operator.ge if self.max_open else operator.gt285 )(rv, self.max)286287 if self.clamp:292 if self.min is not None and rv < self.min:293 return self.min294 if self.max is not None and rv > self.max:295 return self.max296 if (297 self.min is not None298 and rv < self.min299 or self.max is not None300 and rv > self.max301 ):302 if self.min is None:303 self.fail(304 f"{rv} is bigger than the maximum valid value {self.max}.",305 param,306 ctx,307 )308 elif self.max is None:309 self.fail(310 f"{rv} is smaller than the minimum valid value {self.min}.",311 param,312 ctx,313 )314 else:315 self.fail(316 f"{rv} is not in the valid range of {self.min} to {self.max}.",317 param,318 ctx,319 )288 if lt_min:289 return self._clamp(self.min, 1, self.min_open)290291 if gt_max:292 return self._clamp(self.max, -1, self.max_open)293294 if lt_min or gt_max:295 self.fail(f"{rv} is not in the range {self._describe_range()}.", param, ctx)296297 return rv298299 def _clamp(self, bound, dir, open):300 """Find the valid value to clamp to bound in the given301 direction.302303 :param bound: The boundary value.304 :param dir: 1 or -1 indicating the direction to move.305 :param open: If true, the range does not include the bound.306 """307 raise NotImplementedError308309 def _describe_range(self):310 """Describe the range for use in help text."""311 if self.min is None:312 op = "<" if self.max_open else "<="313 return f"x{op}{self.max}"314315 if self.max is None:316 op = ">" if self.min_open else ">="317 return f"x{op}{self.min}"318319 lop = "<" if self.min_open else "<="320 rop = "<" if self.max_open else "<="321 return f"{self.min}{lop}x{rop}{self.max}"322323 def __repr__(self):323 return f"IntRange({self.min}, {self.max})"324 clamp = " clamped" if self.clamp else ""325 return f"<{type(self).__name__} {self._describe_range()}{clamp}>"326327326class FloatParamType(ParamType):327 name = "float"328class IntParamType(_NumberParamTypeBase):329 name = "integer"330 _number_class = int331329 def convert(self, value, param, ctx):330 try:331 return float(value)332 except ValueError:333 self.fail(f"{value} is not a valid floating point value", param, ctx)332 def __repr__(self):333 return "INT"334335336class IntRange(_NumberRangeBase, IntParamType):337 """Restrict an :data:`click.INT` value to a range of accepted338 values. See :ref:`ranges`.339340 If ``min`` or ``max`` are not passed, any value is accepted in that341 direction. If ``min_open`` or ``max_open`` are enabled, the342 corresponding boundary is not included in the range.343344 If ``clamp`` is enabled, a value outside the range is clamped to the345 boundary instead of failing.346347 .. versionchanged:: 8.0348 Added the ``min_open`` and ``max_open`` parameters.349 """350351 name = "integer range"352353 def _clamp(self, bound, dir, open):354 if not open:355 return bound356357 return bound + dir358359360class FloatParamType(_NumberParamTypeBase):361 name = "float"362 _number_class = float363364 def __repr__(self):365 return "FLOAT"366367339class FloatRange(FloatParamType):340 """A parameter that works similar to :data:`click.FLOAT` but restricts341 the value to fit into a range. The default behavior is to fail if the342 value falls outside the range, but it can also be silently clamped343 between the two edges. The exclusive argument permits open intervals.368class FloatRange(_NumberRangeBase, FloatParamType):369 """Restrict a :data:`click.FLOAT` value to a range of accepted370 values. See :ref:`ranges`.371345 See :ref:`ranges` for an example.372 If ``min`` or ``max`` are not passed, any value is accepted in that373 direction. If ``min_open`` or ``max_open`` are enabled, the374 corresponding boundary is not included in the range.375376 If ``clamp`` is enabled, a value outside the range is clamped to the377 boundary instead of failing. This is not supported if either378 boundary is marked ``open``.379380 .. versionchanged:: 8.0381 Added the ``min_open`` and ``max_open`` parameters.382 """383384 name = "float range"385350 def __init__(self, min=None, max=None, clamp=False, exclusive=False):351 self.min = min352 self.max = max353 self.clamp = clamp354 self.exclusive = exclusive386 def __init__(self, min=None, max=None, min_open=False, max_open=False, clamp=False):387 super().__init__(388 min=min, max=max, min_open=min_open, max_open=max_open, clamp=clamp389 )390356 def convert(self, value, param, ctx):357 rv = super().convert(value, param, ctx)391 if (min_open or max_open) and clamp:392 raise TypeError("Clamping is not supported for open bounds.")393359 if self.clamp:360 if self.min is not None and rv < self.min:361 return self.min362 if self.max is not None and rv > self.max:363 return self.max364 less_than = operator.le if self.exclusive else operator.lt365 greater_than = operator.ge if self.exclusive else operator.gt394 def _clamp(self, bound, dir, open):395 if not open:396 return bound397367 if (368 self.min is not None369 and less_than(rv, self.min)370 or self.max is not None371 and greater_than(rv, self.max)372 ):373 if self.min is None:374 self.fail(375 f"{rv} is bigger than the maximum valid value {self.max}.",376 param,377 ctx,378 )379 elif self.max is None:380 self.fail(381 f"{rv} is smaller than the minimum valid value {self.min}.",382 param,383 ctx,384 )385 else:386 self.fail(387 f"{rv} is not in the valid range of {self.min} to {self.max}.",388 param,389 ctx,390 )391 return rv398 # Could use Python 3.9's math.nextafter here, but clamping an399 # open float range doesn't seem to be particularly useful. It's400 # left up to the user to write a callback to do it if needed.401 raise RuntimeError("Clamping is not supported for open bounds.")402393 def __repr__(self):394 return f"FloatRange({self.min}, {self.max})"403396404class BoolParamType(ParamType):405 name = "boolean"406407 def convert(self, value, param, ctx):
340 unmodified lines
modified:tests/test_basic.py-88 removed
410 unmodified lines
411 assert not result.exception412 assert result.output == "2010-06-05T00:00:00\n"413414415def test_int_range_option(runner):416 @click.command()417 @click.option("--x", type=click.IntRange(0, 5))418 def cli(x):419 click.echo(x)420421 result = runner.invoke(cli, ["--x=5"])422 assert not result.exception423 assert result.output == "5\n"424425 result = runner.invoke(cli, ["--x=6"])426 assert result.exit_code == 2427 assert (428 "Invalid value for '--x': 6 is not in the valid range of 0 to 5.\n"429 in result.output430 )431432 @click.command()433 @click.option("--x", type=click.IntRange(0, 5, clamp=True))434 def clamp(x):435 click.echo(x)436437 result = runner.invoke(clamp, ["--x=5"])438 assert not result.exception439 assert result.output == "5\n"440441 result = runner.invoke(clamp, ["--x=6"])442 assert not result.exception443 assert result.output == "5\n"444445 result = runner.invoke(clamp, ["--x=-1"])446 assert not result.exception447 assert result.output == "0\n"448449450def test_float_range_option(runner):451 @click.command()452 @click.option("--x", type=click.FloatRange(0, 5))453 def cli(x):454 click.echo(x)455456 result = runner.invoke(cli, ["--x=5.0"])457 assert not result.exception458 assert result.output == "5.0\n"459460 result = runner.invoke(cli, ["--x=6.0"])461 assert result.exit_code == 2462 assert (463 "Invalid value for '--x': 6.0 is not in the valid range of 0 to 5.\n"464 in result.output465 )466467 @click.command()468 @click.option("--x", type=click.FloatRange(0, 5, clamp=True))469 def clamp(x):470 click.echo(x)471472 result = runner.invoke(clamp, ["--x=5.0"])473 assert not result.exception474 assert result.output == "5.0\n"475476 result = runner.invoke(clamp, ["--x=6.0"])477 assert not result.exception478 assert result.output == "5\n"479480 result = runner.invoke(clamp, ["--x=-1.0"])481 assert not result.exception482 assert result.output == "0\n"483484 @click.command()485 @click.option('--x', type=click.FloatRange(0, 5, exclusive=True))486 def exclude(x):487 click.echo(x)488489 result = runner.invoke(exclude, ['--x=4.99'])490 assert not result.exception491 assert result.output == '4.99\n'492493 result = runner.invoke(exclude, ['--x=5.0'])494 assert result.exit_code == 2495 assert 'Invalid value for "--x": 5.0 is not in the valid range of 0 to 5.\n' \496 in result.output497498 result = runner.invoke(exclude, ['--x=-3e8'])499 assert result.exit_code == 2500 assert 'Invalid value for "--x": -300000000.0 is not in the valid range of 0 to 5.\n' \501 in result.output502415def test_required_option(runner):416 @click.command()417 @click.option("--foo", required=True)418 def cli(foo):
92 unmodified lines
modified:tests/test_options.py+15 added-12 removed
62 unmodified lines
63 assert result.output == "verbosity=3\n"6465 result = runner.invoke(cli, ["-vvvv"])66 assert result.exception67 assert (68 "Invalid value for '-v': 4 is not in the valid range of 0 to 3."69 in result.output70 )67 assert "Invalid value for '-v': 4 is not in the range 0<=x<=3." in result.output6869 result = runner.invoke(cli, [])70 assert not result.exception71 assert result.output == "verbosity=0\n"
140 unmodified lines
212 assert "lambda" not in result.output213 assert "(current user)" in result.output214215219def test_intrange_default_help_text(runner):220 @click.command()221 @click.option("--count", type=click.IntRange(1, 32), show_default=True, default=1)222 def cmd(arg):223 click.echo(arg)216@pytest.mark.parametrize(217 ("type", "expect"),218 [219 (click.IntRange(1, 32), "1<=x<=32"),220 (click.IntRange(1, 32, min_open=True, max_open=True), "1<x<32"),221 (click.IntRange(1), "x>=1"),222 (click.IntRange(max=32), "x<=32"),223 ],224)225def test_intrange_default_help_text(runner, type, expect):226 option = click.Option(["--count"], type=type, show_default=True, default=1)227 context = click.Context(click.Command("test"))228 result = option.get_help_record(context)[1]229 assert expect in result230225 result = runner.invoke(cmd, ["--help"])226 assert "1-32 inclusive" in result.output231228232def test_toupper_envvar_prefix(runner):233 @click.command()234 @click.option("--arg")235 def cmd(arg):
369 unmodified lines
added:tests/test_types.py+56 added
1import pytest23import click456@pytest.mark.parametrize(7 ("type", "value", "expect"),8 [9 (click.IntRange(0, 5), "3", 3),10 (click.IntRange(5), "5", 5),11 (click.IntRange(5), "100", 100),12 (click.IntRange(max=5), "5", 5),13 (click.IntRange(max=5), "-100", -100),14 (click.IntRange(0, clamp=True), "-1", 0),15 (click.IntRange(max=5, clamp=True), "6", 5),16 (click.IntRange(0, min_open=True, clamp=True), "0", 1),17 (click.IntRange(max=5, max_open=True, clamp=True), "5", 4),18 (click.FloatRange(0.5, 1.5), "1.2", 1.2),19 (click.FloatRange(0.5, min_open=True), "0.51", 0.51),20 (click.FloatRange(max=1.5, max_open=True), "1.49", 1.49),21 (click.FloatRange(0.5, clamp=True), "-0.0", 0.5),22 (click.FloatRange(max=1.5, clamp=True), "inf", 1.5),23 ],24)25def test_range(type, value, expect):26 assert type.convert(value, None, None) == expect272829@pytest.mark.parametrize(30 ("type", "value", "expect"),31 [32 (click.IntRange(0, 5), "6", "6 is not in the range 0<=x<=5."),33 (click.IntRange(5), "4", "4 is not in the range x>=5."),34 (click.IntRange(max=5), "6", "6 is not in the range x<=5."),35 (click.IntRange(0, 5, min_open=True), 0, "0<x<=5"),36 (click.IntRange(0, 5, max_open=True), 5, "0<=x<5"),37 (click.FloatRange(0.5, min_open=True), 0.5, "x>0.5"),38 (click.FloatRange(max=1.5, max_open=True), 1.5, "x<1.5"),39 ],40)41def test_range_fail(type, value, expect):42 with pytest.raises(click.BadParameter) as exc_info:43 type.convert(value, None, None)4445 assert expect in exc_info.value.message464748def test_float_range_no_clamp_open():49 with pytest.raises(TypeError):50 click.FloatRange(0, 1, max_open=True, clamp=True)5152 sneaky = click.FloatRange(0, 1, max_open=True)53 sneaky.clamp = True5455 with pytest.raises(RuntimeError):56 sneaky.convert("1.5", None, None)
modified:CHANGES.rst+5 added-3 removed
16 unmodified lines
17 ``importlib_metadata`` backport) instead of ``pkg_resources``.18 :issue:`1582`19- If validation fails for a prompt with ``hide_input=True``, the value20 is not shown in the error message. :issue:`1460`21- An ``IntRange`` option shows the accepted range in its help text.22 :issue:`1525`23- ``FloatRange`` min and max can be exclusive. :issue:`1100`21- An ``IntRange`` or ``FloatRange`` option shows the accepted range in22 its help text. :issue:`1525`, :pr:`1303`23- ``IntRange`` and ``FloatRange`` bounds can be open (``<``) instead24 of closed (``<=``) by setting ``min_open`` and ``max_open``. Error25 messages have changed to reflect this. :issue:`1100`26- An option defined with duplicate flag names (``"--foo/--foo"``)27 raises a ``ValueError``. :issue:`1465`28- ``echo()`` will not fail when using pytest's ``capsys`` fixture on29 Windows. :issue:`1590`
685 unmodified lines