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
Provenance
- Commit
d77a0ae- Tree
2ae7d5b- Author
David Lord <davidism@gmail.com>- Committer
David Lord <davidism@gmail.com>- Parent
75b708a
7 files changed+209 added−231 removed
modified:docs/options.rst+16 added-21 removed
773 unmodified lines774 775 Range Options776 -------------777 778-A special mention should go to the :class:`IntRange` type, which works very779-similarly to the :data:`INT` type, but restricts the value to fall into a780-specific range (inclusive on both edges). It has two modes:778+The :class:`IntRange` type extends the :data:`INT` type to ensure the779+value is contained in the given range. The :class:`FloatRange` type does780+the same for :data:`FLOAT`.781 782-- 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).782+If ``min`` or ``max`` is omitted, that side is *unbounded*. Any value in783+that direction is accepted. By default, both bounds are *closed*, which784+means the boundary value is included in the accepted range. ``min_open``785+and ``max_open`` can be used to exclude that boundary from the range.786 789-Example:787+If ``clamp`` mode is enabled, a value that is outside the range is set788+to the boundary instead of failing. For example, the range ``0, 5``789+would return ``5`` for the value ``10``, or ``0`` for the value ``-1``.790+When using :class:`FloatRange`, ``clamp`` can only be enabled if both791+bounds are *closed* (the default).792 793 .. click:example::794 795 @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)800 799- if __name__ == '__main__':800- repeat()801-802-And from the command line:803-801 .. click:run::802 806- 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'])805 809-If you pass ``None`` for any of the edges, it means that the range is open810-at that side.806 807 Callbacks for Validation808 ------------------------809 38 unmodified linesmodified:src/click/core.py+6 added-3 removed
21 unmodified lines22 from .parser import split_opt23 from .termui import confirm24 from .termui import prompt25 from .termui import style26+from .types import _NumberRangeBase27 from .types import BOOL28 from .types import convert_type29 from .types import IntRange30 from .utils import _detect_program_name2029 unmodified lines2060 else:2061 default_string = self.default2062 extra.append(f"default: {default_string}")2063 2063- 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()2066 2067+ if range_str:2068+ extra.append(range_str)2069+2070 if self.required:2071 extra.append("required")2072 if extra:2073 extra_str = ";".join(extra)133 unmodified linesmodified:src/click/types.py+111 added-104 removed
1 import os2-import operator2 import stat3 from datetime import datetime4 5 from ._compat import _get_argv_encoding248 unmodified lines254 def __repr__(self):255 return "DateTime"256 257 259-class IntParamType(ParamType):260- name = "integer"258+class _NumberParamTypeBase(ParamType):259+ _number_class = None260 261 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)266 268- def __repr__(self):269- return "INT"267 271-272-class 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.277-278- See :ref:`ranges` for an example.279- """280-281- name = "integer range"282-283- def __init__(self, min=None, max=None, clamp=False):268+class _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 = clamp275 276 def convert(self, value, param, ctx):277+ import operator278+279 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)286 287 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)290+291+ if gt_max:292+ return self._clamp(self.max, -1, self.max_open)293+294+ if lt_min or gt_max:295+ self.fail(f"{rv} is not in the range {self._describe_range()}.", param, ctx)296+297 return rv298 299+ def _clamp(self, bound, dir, open):300+ """Find the valid value to clamp to bound in the given301+ direction.302+303+ :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 NotImplementedError308+309+ 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}"314+315+ if self.max is None:316+ op = ">" if self.min_open else ">="317+ return f"x{op}{self.min}"318+319+ lop = "<" if self.min_open else "<="320+ rop = "<" if self.max_open else "<="321+ return f"{self.min}{lop}x{rop}{self.max}"322+323 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}>"326 327 326-class FloatParamType(ParamType):327- name = "float"328+class IntParamType(_NumberParamTypeBase):329+ name = "integer"330+ _number_class = int331 329- 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"334 335+336+class IntRange(_NumberRangeBase, IntParamType):337+ """Restrict an :data:`click.INT` value to a range of accepted338+ values. See :ref:`ranges`.339+340+ 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.343+344+ If ``clamp`` is enabled, a value outside the range is clamped to the345+ boundary instead of failing.346+347+ .. versionchanged:: 8.0348+ Added the ``min_open`` and ``max_open`` parameters.349+ """350+351+ name = "integer range"352+353+ def _clamp(self, bound, dir, open):354+ if not open:355+ return bound356+357+ return bound + dir358+359+360+class FloatParamType(_NumberParamTypeBase):361+ name = "float"362+ _number_class = float363+364 def __repr__(self):365 return "FLOAT"366 367 339-class 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.368+class FloatRange(_NumberRangeBase, FloatParamType):369+ """Restrict a :data:`click.FLOAT` value to a range of accepted370+ values. See :ref:`ranges`.371 345- 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.375+376+ 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``.379+380+ .. versionchanged:: 8.0381+ Added the ``min_open`` and ``max_open`` parameters.382 """383 384 name = "float range"385 350- 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+ )390 356- 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.")393 359- 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 bound397 367- 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.")402 393- def __repr__(self):394- return f"FloatRange({self.min}, {self.max})"403 396-404 class BoolParamType(ParamType):405 name = "boolean"406 407 def convert(self, value, param, ctx):340 unmodified linesmodified:tests/test_basic.py-88 removed
410 unmodified lines411 assert not result.exception412 assert result.output == "2010-06-05T00:00:00\n"413 414 415-def 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)420-421- result = runner.invoke(cli, ["--x=5"])422- assert not result.exception423- assert result.output == "5\n"424-425- 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- )431-432- @click.command()433- @click.option("--x", type=click.IntRange(0, 5, clamp=True))434- def clamp(x):435- click.echo(x)436-437- result = runner.invoke(clamp, ["--x=5"])438- assert not result.exception439- assert result.output == "5\n"440-441- result = runner.invoke(clamp, ["--x=6"])442- assert not result.exception443- assert result.output == "5\n"444-445- result = runner.invoke(clamp, ["--x=-1"])446- assert not result.exception447- assert result.output == "0\n"448-449-450-def 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)455-456- result = runner.invoke(cli, ["--x=5.0"])457- assert not result.exception458- assert result.output == "5.0\n"459-460- 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- )466-467- @click.command()468- @click.option("--x", type=click.FloatRange(0, 5, clamp=True))469- def clamp(x):470- click.echo(x)471-472- result = runner.invoke(clamp, ["--x=5.0"])473- assert not result.exception474- assert result.output == "5.0\n"475-476- result = runner.invoke(clamp, ["--x=6.0"])477- assert not result.exception478- assert result.output == "5\n"479-480- result = runner.invoke(clamp, ["--x=-1.0"])481- assert not result.exception482- assert result.output == "0\n"483-484- @click.command()485- @click.option('--x', type=click.FloatRange(0, 5, exclusive=True))486- def exclude(x):487- click.echo(x)488-489- result = runner.invoke(exclude, ['--x=4.99'])490- assert not result.exception491- assert result.output == '4.99\n'492-493- 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.output497-498- 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.output502-415 def test_required_option(runner):416 @click.command()417 @click.option("--foo", required=True)418 def cli(foo):92 unmodified linesmodified:tests/test_options.py+15 added-12 removed
62 unmodified lines63 assert result.output == "verbosity=3\n"64 65 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.output68 69 result = runner.invoke(cli, [])70 assert not result.exception71 assert result.output == "verbosity=0\n"140 unmodified lines212 assert "lambda" not in result.output213 assert "(current user)" in result.output214 215 219-def 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+)225+def 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 result230 225- result = runner.invoke(cmd, ["--help"])226- assert "1-32 inclusive" in result.output231 228-232 def test_toupper_envvar_prefix(runner):233 @click.command()234 @click.option("--arg")235 def cmd(arg):369 unmodified linesadded:tests/test_types.py+56 added
1+import pytest2+3+import click4+5+6+@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+)25+def test_range(type, value, expect):26+ assert type.convert(value, None, None) == expect27+28+29+@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+)41+def test_range_fail(type, value, expect):42+ with pytest.raises(click.BadParameter) as exc_info:43+ type.convert(value, None, None)44+45+ assert expect in exc_info.value.message46+47+48+def test_float_range_no_clamp_open():49+ with pytest.raises(TypeError):50+ click.FloatRange(0, 1, max_open=True, clamp=True)51+52+ sneaky = click.FloatRange(0, 1, max_open=True)53+ sneaky.clamp = True54+55+ with pytest.raises(RuntimeError):56+ sneaky.convert("1.5", None, None)modified:CHANGES.rst+5 added-3 removed
16 unmodified lines17 ``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