Skip to content

Commit

Permalink
Merge pull request #1914 from pallets/custom-type-value
Browse files Browse the repository at this point in the history
document values passed to types
  • Loading branch information
davidism committed May 19, 2021
2 parents ba9bb3c + 0c108f2 commit 329b100
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 7 deletions.
2 changes: 2 additions & 0 deletions CHANGES.rst
Expand Up @@ -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
Expand Down
15 changes: 8 additions & 7 deletions docs/parameters.rst
Expand Up @@ -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)
Expand All @@ -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.

0 comments on commit 329b100

Please sign in to comment.