From 0c108f22c7f87f6ea4657ffa2a54516dcd3548f6 Mon Sep 17 00:00:00 2001 From: David Lord Date: Wed, 19 May 2021 07:47:46 -0700 Subject: [PATCH] document values passed to types --- CHANGES.rst | 2 ++ docs/parameters.rst | 15 ++++++++------- 2 files changed, 10 insertions(+), 7 deletions(-) diff --git a/CHANGES.rst b/CHANGES.rst index 7f103d054..b59fc443f 100644 --- a/CHANGES.rst +++ b/CHANGES.rst @@ -18,6 +18,8 @@ Unreleased line values are given. :issue:`1903` - Flag options guess their type from ``flag_value`` if given, like regular options do from ``default``. :issue:`1886` +- Added documentation that custom parameter types may be passed + already valid values in addition to strings. :issue:`1898` Version 8.0.0 diff --git a/docs/parameters.rst b/docs/parameters.rst index 27c84ea6f..b3604e750 100644 --- a/docs/parameters.rst +++ b/docs/parameters.rst @@ -118,19 +118,15 @@ integers. name = "integer" def convert(self, value, param, ctx): + if isinstance(value, int): + return value + try: if value[:2].lower() == "0x": return int(value[2:], 16) elif value[:1] == "0": return int(value, 8) return int(value, 10) - except TypeError: - self.fail( - "expected string for int() conversion, got " - f"{value!r} of type {type(value).__name__}", - param, - ctx, - ) except ValueError: self.fail(f"{value!r} is not a valid integer", param, ctx) @@ -140,3 +136,8 @@ The :attr:`~ParamType.name` attribute is optional and is used for documentation. Call :meth:`~ParamType.fail` if conversion fails. The ``param`` and ``ctx`` arguments may be ``None`` in some cases such as prompts. + +Values from user input or the command line will be strings, but default +values and Python arguments may already be the correct type. The custom +type should check at the top if the value is already valid and pass it +through to support those cases.