Merge pull request #1303 from robintully/issue_1110_open_interval
Before adoption: this commit came in with the history the project adopted, so no landing records it.
allow open intervals on float range
authored by David Lord · committed by GitHub · parents 01fc511, d77a0ae · Browse files · 7 files·+209 added−207 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−207 removed
- tests:+71 added−82 removed
- other:+138 added−125 removed
Provenance
- Commit
ca75bab- Tree
5561fa0- Author
David Lord <davidism@gmail.com>- Committer
GitHub <noreply@github.com>- Parent 1
01fc511- Parent 2
d77a0ae
7 files changed+209 added−207 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-99 removed
253 unmodified lines254 def __repr__(self):255 return "DateTime"256 257 258-class IntParamType(ParamType):259- name = "integer"258+class _NumberParamTypeBase(ParamType):259+ _number_class = None260 261 def convert(self, value, param, ctx):262 try:263- return int(value)263+ return self._number_class(value)264 except ValueError:265- 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 267- def __repr__(self):268- return "INT"267 270-271-class IntRange(IntParamType):272- """A parameter that works similar to :data:`click.INT` but restricts273- the value to fit into a range. The default behavior is to fail if the274- value falls outside the range, but it can also be silently clamped275- between the two edges.276-277- See :ref:`ranges` for an example.278- """279-280- name = "integer range"281-282- 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:291- if self.min is not None and rv < self.min:292- return self.min293- if self.max is not None and rv > self.max:294- return self.max295- if (296- self.min is not None297- and rv < self.min298- or self.max is not None299- and rv > self.max300- ):301- if self.min is None:302- self.fail(303- f"{rv} is bigger than the maximum valid value {self.max}.",304- param,305- ctx,306- )307- elif self.max is None:308- self.fail(309- f"{rv} is smaller than the minimum valid value {self.min}.",310- param,311- ctx,312- )313- else:314- self.fail(315- f"{rv} is not in the valid range of {self.min} to {self.max}.",316- param,317- ctx,318- )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):322- 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 325-class FloatParamType(ParamType):326- name = "float"328+class IntParamType(_NumberParamTypeBase):329+ name = "integer"330+ _number_class = int331 328- def convert(self, value, param, ctx):329- try:330- return float(value)331- except ValueError:332- 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 338-class FloatRange(FloatParamType):339- """A parameter that works similar to :data:`click.FLOAT` but restricts340- the value to fit into a range. The default behavior is to fail if the341- value falls outside the range, but it can also be silently clamped342- between the two edges.368+class FloatRange(_NumberRangeBase, FloatParamType):369+ """Restrict a :data:`click.FLOAT` value to a range of accepted370+ values. See :ref:`ranges`.371 344- 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 349- def __init__(self, min=None, max=None, clamp=False):350- self.min = min351- self.max = max352- self.clamp = clamp386+ 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 354- def convert(self, value, param, ctx):355- 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 357- if self.clamp:358- if self.min is not None and rv < self.min:359- return self.min360- if self.max is not None and rv > self.max:361- return self.max362- if (363- self.min is not None364- and rv < self.min365- or self.max is not None366- and rv > self.max367- ):368- if self.min is None:369- self.fail(370- f"{rv} is bigger than the maximum valid value {self.max}.",371- param,372- ctx,373- )374- elif self.max is None:375- self.fail(376- f"{rv} is smaller than the minimum valid value {self.min}.",377- param,378- ctx,379- )380- else:381- self.fail(382- f"{rv} is not in the valid range of {self.min} to {self.max}.",383- param,384- ctx,385- )386- return rv394+ def _clamp(self, bound, dir, open):395+ if not open:396+ return bound397 388- def __repr__(self):389- return f"FloatRange({self.min}, {self.max})"398+ # 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 403 404 class BoolParamType(ParamType):405 name = "boolean"342 unmodified linesmodified:tests/test_basic.py-70 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-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-2 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`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