ParameterSource is an Enum subclass
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by Alan Velasco · committed by David Lord · parent d15d0cd · Browse files · 6 files·+88 added−107 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Trailers
- Co-authored-by: David Lord <davidism@gmail.com>
Diff stats
6 files+88 added−107 removed
- tests:+42 added−57 removed
- other:+46 added−50 removed
Provenance
- Commit
3852f41- Tree
d5170dd- Author
Alan Velasco <AlanVelasco.A@gmail.com>- Committer
David Lord <davidism@gmail.com>- Parent
d15d0cd
6 files changed+88 added−107 removed
modified:docs/advanced.rst+5 added-3 removed
384 unmodified lines385 -----------------------------------386 387 In some situations it's helpful to understand whether or not an option388 or parameter came from the command line, the environment, the default389-value, or the default_map. The :meth:`Context.get_parameter_source`390-method can be used to find this out.389+value, or :attr:`Context.default_map`. The390+:meth:`Context.get_parameter_source` method can be used to find this391+out. It will return a member of the :class:`~click.core.ParameterSource`392+enum.393 394 .. click:example::395 396 @click.command()397 @click.argument('port', nargs=1, default=8080, envvar="PORT")398 @click.pass_context399 def cli(ctx, port):400 source = ctx.get_parameter_source("port")399- click.echo(f"Port came from {source}")401+ click.echo(f"Port came from {source.name}")402 403 .. click:run::404 405 invoke(cli, prog_name='cli', args=['8080'])79 unmodified linesmodified:docs/api.rst+5 added
106 unmodified lines107 :members:108 109 .. autofunction:: get_current_context110 111+.. autoclass:: click.core.ParameterSource112+ :members:113+ :member-order: bysource114+115+116 Types117 -----118 119 .. autodata:: STRING85 unmodified linesmodified:src/click/core.py+35 added-47 removed
1+import enum2 import errno3 import inspect4 import os5 import sys126 unmodified lines132 133 return sorted(declaration_order, key=sort_key)134 135 135-class ParameterSource:136- """This is an enum that indicates the source of a command line parameter.136+class ParameterSource(enum.Enum):137+ """This is an :class:`~enum.Enum` that indicates the source of a138+ parameter's value.139 138- The enum has one of the following values: COMMANDLINE,139- ENVIRONMENT, DEFAULT, DEFAULT_MAP. The DEFAULT indicates that the140- default value in the decorator was used. This class should be141- converted to an enum when Python 2 support is dropped.140+ Use :meth:`click.Context.get_parameter_source` to get the141+ source for a parameter by name.142+143+ .. versionchanged:: 8.0144+ Use :class:`~enum.Enum` and drop the ``validate`` method.145 """146 144- COMMANDLINE = "COMMANDLINE"145- ENVIRONMENT = "ENVIRONMENT"146- DEFAULT = "DEFAULT"147- DEFAULT_MAP = "DEFAULT_MAP"147+ COMMANDLINE = enum.auto()148+ """The value was provided by the command line args."""149+ ENVIRONMENT = enum.auto()150+ """The value was provided with an environment variable."""151+ DEFAULT = enum.auto()152+ """Used the default specified by the parameter."""153+ DEFAULT_MAP = enum.auto()154+ """Used a default provided by :attr:`Context.default_map`."""155 149- VALUES = {COMMANDLINE, ENVIRONMENT, DEFAULT, DEFAULT_MAP}156 151- @classmethod152- def validate(cls, value):153- """Validate that the specified value is a valid enum.154-155- This method will raise a ValueError if the value is156- not a valid enum.157-158- :param value: the string value to verify159- """160- if value not in cls.VALUES:161- raise ValueError(162- f"Invalid ParameterSource value: {value!r}. Valid"163- f" values are: {','.join(cls.VALUES)}"164- )165-166-157 class Context:158 """The context is a special internal object that holds state relevant159 for the script execution at every single level. It's normally invisible160 to commands unless they opt-in to getting access to it.245 unmodified lines406 self.show_default = show_default407 408 self._close_callbacks = []409 self._depth = 0420- self._source_by_paramname = {}410+ self._parameter_source = {}411 self._exit_stack = ExitStack()412 413 def to_info_dict(self):414 """Gather information that could be useful for a tool generating302 unmodified lines717 718 return self.invoke(cmd, **kwargs)719 720 def set_parameter_source(self, name, source):731- """Set the source of a parameter.721+ """Set the source of a parameter. This indicates the location722+ from which the value of the parameter was obtained.723 733- This indicates the location from which the value of the734- parameter was obtained.735-736- :param name: the name of the command line parameter737- :param source: the source of the command line parameter, which738- should be a valid ParameterSource value724+ :param name: The name of the parameter.725+ :param source: A member of :class:`~click.core.ParameterSource`.726 """740- ParameterSource.validate(source)741- self._source_by_paramname[name] = source727+ self._parameter_source[name] = source728 729 def get_parameter_source(self, name):744- """Get the source of a parameter.730+ """Get the source of a parameter. This indicates the location731+ from which the value of the parameter was obtained.732 746- This indicates the location from which the value of the747- parameter was obtained. This can be useful for determining748- when a user specified an option on the command line that is749- the same as the default. In that case, the source would be750- ParameterSource.COMMANDLINE, even though the value of the751- parameter was equivalent to the default.733+ This can be useful for determining when a user specified a value734+ on the command line that is the same as the default value. It735+ will be :attr:`~click.core.ParameterSource.DEFAULT` only if the736+ value was actually taken from the default.737 753- :param name: the name of the command line parameter754- :returns: the source738+ :param name: The name of the parameter.739 :rtype: ParameterSource740 """757- return self._source_by_paramname[name]741+ return self._parameter_source[name]742 743 744 class BaseCommand:745 """The base command implements the minimal API contract of commands.1170 unmodified lines1916 1917 def consume_value(self, ctx, opts):1918 value = opts.get(self.name)1919 source = ParameterSource.COMMANDLINE1920+1921 if value is None:1922 value = self.value_from_envvar(ctx)1923 source = ParameterSource.ENVIRONMENT1924+1925 if value is None:1926 value = ctx.lookup_default(self.name)1927 source = ParameterSource.DEFAULT_MAP1928+1929 if value is not None:1930 ctx.set_parameter_source(self.name, source)1931+1932 return value1933 1934 def type_cast_value(self, ctx, value):1935 """Given a value this runs it properly through the type system.558 unmodified linesmodified:tests/test_context.py+41 added-56 removed
295 unmodified lines296 297 assert cli.main([], "test_exit_not_standalone", standalone_mode=False) == 0298 299 300-def test_parameter_source_default(runner):300+@pytest.mark.parametrize(301+ ("option_args", "invoke_args", "expect"),302+ [303+ pytest.param({}, {}, ParameterSource.DEFAULT, id="default"),304+ pytest.param(305+ {},306+ {"default_map": {"option": 1}},307+ ParameterSource.DEFAULT_MAP,308+ id="default_map",309+ ),310+ pytest.param(311+ {},312+ {"args": ["-o", "1"]},313+ ParameterSource.COMMANDLINE,314+ id="commandline short",315+ ),316+ pytest.param(317+ {},318+ {"args": ["--option", "1"]},319+ ParameterSource.COMMANDLINE,320+ id="commandline long",321+ ),322+ pytest.param(323+ {},324+ {"auto_envvar_prefix": "TEST", "env": {"TEST_OPTION": "1"}},325+ ParameterSource.ENVIRONMENT,326+ id="environment auto",327+ ),328+ pytest.param(329+ {"envvar": "NAME"},330+ {"env": {"NAME": "1"}},331+ ParameterSource.ENVIRONMENT,332+ id="environment manual",333+ ),334+ ],335+)336+def test_parameter_source(runner, option_args, invoke_args, expect):337 @click.command()338 @click.pass_context303- @click.option("-o", "--option", default=1)339+ @click.option("-o", "--option", default=1, **option_args)340 def cli(ctx, option):305- click.echo(ctx.get_parameter_source("option"))341+ return ctx.get_parameter_source("option")342 307- rv = runner.invoke(cli)308- assert rv.output.rstrip() == ParameterSource.DEFAULT309-310-311-def test_parameter_source_default_map(runner):312- @click.command()313- @click.pass_context314- @click.option("-o", "--option", default=1)315- def cli(ctx, option):316- click.echo(ctx.get_parameter_source("option"))317-318- rv = runner.invoke(cli, default_map={"option": 1})319- assert rv.output.rstrip() == ParameterSource.DEFAULT_MAP320-321-322-def test_parameter_source_commandline(runner):323- @click.command()324- @click.pass_context325- @click.option("-o", "--option", default=1)326- def cli(ctx, option):327- click.echo(ctx.get_parameter_source("option"))328-329- rv = runner.invoke(cli, ["-o", "1"])330- assert rv.output.rstrip() == ParameterSource.COMMANDLINE331- rv = runner.invoke(cli, ["--option", "1"])332- assert rv.output.rstrip() == ParameterSource.COMMANDLINE333-334-335-def test_parameter_source_environment(runner):336- @click.command()337- @click.pass_context338- @click.option("-o", "--option", default=1)339- def cli(ctx, option):340- click.echo(ctx.get_parameter_source("option"))341-342- rv = runner.invoke(cli, auto_envvar_prefix="TEST", env={"TEST_OPTION": "1"})343- assert rv.output.rstrip() == ParameterSource.ENVIRONMENT344-345-346-def test_parameter_source_environment_variable_specified(runner):347- @click.command()348- @click.pass_context349- @click.option("-o", "--option", default=1, envvar="NAME")350- def cli(ctx, option):351- click.echo(ctx.get_parameter_source("option"))352-353- rv = runner.invoke(cli, env={"NAME": "1"})354- assert rv.output.rstrip() == ParameterSource.ENVIRONMENT355-356-357-def test_validate_parameter_source():358- with pytest.raises(ValueError):359- ParameterSource.validate("NOT_A_VALID_PARAMETER_SOURCE")343+ rv = runner.invoke(cli, standalone_mode=False, **invoke_args)344+ assert rv.return_value == expectmodified:tests/test_imports.py+1 added-1 removed
43 unmodified lines44 "colorama",45 "errno",46 "fcntl",47 "datetime",48- "pipes",48+ "enum",49 }50 51 if WIN:52 ALLOWED_IMPORTS.update(["ctypes", "ctypes.wintypes", "msvcrt", "time", "zlib"])14 unmodified linesmodified:CHANGES.rst+1 added
108 unmodified lines109 110 - Extra context settings (``obj=...``, etc.) are passed on to the111 completion system. :issue:`942`112 - Include ``--help`` option in completion. :pr:`1504`113+- ``ParameterSource`` is an ``enum.Enum`` subclass. :issue:`1530`114 115 116 Version 7.1.2117 -------------635 unmodified lines