Skip to content
Myr

Allow a callable default to have its own string representation

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

As it was before 78a62b37c956e71b32689a0d5c75a684aa9ab56d. A callable can also be an object with __call__ and __str__ defined, in which case it makes sense to use it. Don't try too hard to show something else instead, because the developer most likely knows what he (or she) is doing. https://github.com/pallets/click/issues/2099

authored by Krzysztof Kotlenga · committed by David Lord · parent 08a825d · Browse files · 3 files+17 added−1 removed
This commit

State

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

Trailers

  • https: //github.com/pallets/click/issues/2099

Diff stats

3 files+17 added−1 removed

  • tests:+13 added−0 removed
  • other:+4 added−1 removed

3 files+17 added−1 removed

modified:src/click/core.py+2 added-1 removed
1import enum2import errno3import inspect4import os5import sys6import typing as t7from collections import abc
2711 unmodified lines
2719 if show_default_is_str:2720 default_string = f"({self.show_default})"2721 elif isinstance(default_value, (list, tuple)):2722 default_string = ", ".join(str(d) for d in default_value)2722 elif callable(default_value):2723 elif inspect.isfunction(default_value):2724 default_string = _("(dynamic)")2725 elif self.is_bool_flag and self.secondary_opts:2726 # For boolean flags that have distinct True/False opts,2727 # use the opt without prefix instead of the value.
226 unmodified lines
modified:tests/test_options.py+13 added
303 unmodified lines
304 assert "lambda" not in result.output305 assert "(current user)" in result.output306307308def test_dynamic_default_help_special_method(runner):309 class Value:310 def __call__(self):311 return 42312313 def __str__(self):314 return "special value"315316 opt = click.Option(["-a"], default=Value(), show_default=True)317 ctx = click.Context(click.Command("cli"))318 assert "special value" in opt.get_help_record(ctx)[1]319320321@pytest.mark.parametrize(322 ("type", "expect"),323 [324 (click.IntRange(1, 32), "1<=x<=32"),
530 unmodified lines
modified:CHANGES.rst+2 added
7 unmodified lines
8- ``open_file`` recognizes ``Path("-")`` as a standard stream, the9 same as the string ``"-"``. :issue:`2106`10- The ``option`` and ``argument`` decorators preserve the type11 annotation of the decorated function. :pr:`2155`12- A callable default value can customize its help text by overriding13 ``__str__`` instead of always showing ``(dynamic)``. :issue:`2099`141516Version 8.0.317-------------
930 unmodified lines