Skip to content
Myr

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

6 files+88 added−107 removed

modified:docs/advanced.rst+5 added-3 removed
384 unmodified lines
385-----------------------------------386387In some situations it's helpful to understand whether or not an option388or parameter came from the command line, the environment, the default389value, or the default_map. The :meth:`Context.get_parameter_source`390method can be used to find this out.389value, or :attr:`Context.default_map`. The390:meth:`Context.get_parameter_source` method can be used to find this391out. It will return a member of the :class:`~click.core.ParameterSource`392enum.393394.. click:example::395396 @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}")402403.. click:run::404405 invoke(cli, prog_name='cli', args=['8080'])
79 unmodified lines
modified:docs/api.rst+5 added
106 unmodified lines
107 :members:108109.. autofunction:: get_current_context110111.. autoclass:: click.core.ParameterSource112 :members:113 :member-order: bysource114115116Types117-----118119.. autodata:: STRING
85 unmodified lines
modified:src/click/core.py+35 added-47 removed
1import enum2import errno3import inspect4import os5import sys
126 unmodified lines
132133 return sorted(declaration_order, key=sort_key)134135135class ParameterSource:136 """This is an enum that indicates the source of a command line parameter.136class ParameterSource(enum.Enum):137 """This is an :class:`~enum.Enum` that indicates the source of a138 parameter's value.139138 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.142143 .. versionchanged:: 8.0144 Use :class:`~enum.Enum` and drop the ``validate`` method.145 """146144 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`."""155149 VALUES = {COMMANDLINE, ENVIRONMENT, DEFAULT, DEFAULT_MAP}156151 @classmethod152 def validate(cls, value):153 """Validate that the specified value is a valid enum.154155 This method will raise a ValueError if the value is156 not a valid enum.157158 :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 )165166157class 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 lines
406 self.show_default = show_default407408 self._close_callbacks = []409 self._depth = 0420 self._source_by_paramname = {}410 self._parameter_source = {}411 self._exit_stack = ExitStack()412413 def to_info_dict(self):414 """Gather information that could be useful for a tool generating
302 unmodified lines
717718 return self.invoke(cmd, **kwargs)719720 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.723733 This indicates the location from which the value of the734 parameter was obtained.735736 :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] = source728729 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.732746 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.737753 :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]742743744class BaseCommand:745 """The base command implements the minimal API contract of commands.
1170 unmodified lines
19161917 def consume_value(self, ctx, opts):1918 value = opts.get(self.name)1919 source = ParameterSource.COMMANDLINE19201921 if value is None:1922 value = self.value_from_envvar(ctx)1923 source = ParameterSource.ENVIRONMENT19241925 if value is None:1926 value = ctx.lookup_default(self.name)1927 source = ParameterSource.DEFAULT_MAP19281929 if value is not None:1930 ctx.set_parameter_source(self.name, source)19311932 return value19331934 def type_cast_value(self, ctx, value):1935 """Given a value this runs it properly through the type system.
558 unmodified lines
modified:tests/test_context.py+41 added-56 removed
295 unmodified lines
296297 assert cli.main([], "test_exit_not_standalone", standalone_mode=False) == 0298299300def 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)336def 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")342307 rv = runner.invoke(cli)308 assert rv.output.rstrip() == ParameterSource.DEFAULT309310311def 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"))317318 rv = runner.invoke(cli, default_map={"option": 1})319 assert rv.output.rstrip() == ParameterSource.DEFAULT_MAP320321322def 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"))328329 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.COMMANDLINE333334335def 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"))341342 rv = runner.invoke(cli, auto_envvar_prefix="TEST", env={"TEST_OPTION": "1"})343 assert rv.output.rstrip() == ParameterSource.ENVIRONMENT344345346def 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"))352353 rv = runner.invoke(cli, env={"NAME": "1"})354 assert rv.output.rstrip() == ParameterSource.ENVIRONMENT355356357def 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 == expect
modified:tests/test_imports.py+1 added-1 removed
43 unmodified lines
44 "colorama",45 "errno",46 "fcntl",47 "datetime",48 "pipes",48 "enum",49}5051if WIN:52 ALLOWED_IMPORTS.update(["ctypes", "ctypes.wintypes", "msvcrt", "time", "zlib"])
14 unmodified lines
modified:CHANGES.rst+1 added
108 unmodified lines
109110- 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`114115116Version 7.1.2117-------------
635 unmodified lines