Skip to content
Myr

fix custom type docs indentation

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

authored by David Lord · committed by David Lord · parent b6d421d · Browse files · 1 file+20 added−13 removed
This commit

State

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

Diff stats

1 file+20 added−13 removed

  • other:+20 added−13 removed

1 file+20 added−13 removed

modified:docs/parameters.rst+20 added-13 removed
108 unmodified lines
109Implementing Custom Types110-------------------------111112To implement a custom type, you need to subclass the :class:`ParamType`113class. Types can be invoked with or without context and parameter object,114which is why they need to be able to deal with this.113class. Override the :meth:`~ParamType.convert` method to convert the114value from a string to the correct type.115116The following code implements an integer type that accepts hex and octal117numbers in addition to normal integers, and converts them into regular118integers::118integers.119120.. code-block:: python121122 import click123124 class BasedIntParamType(click.ParamType):123 name = 'integer'125 name = "integer"126127 def convert(self, value, param, ctx):128 try:127 if value[:2].lower() == '0x':129 if value[:2].lower() == "0x":130 return int(value[2:], 16)129 elif value[:1] == '0':131 elif value[:1] == "0":132 return int(value, 8)133 return int(value, 10)132 except TypeError:133 self.fail('expected string for int() conversion, got %s of type %s'134 % (value, type(value).__name__), param, ctx)134 except TypeError:135 self.fail(136 "expected string for int() conversion, got "137 f"{value!r} of type {type(value).__name__}",138 param,139 ctx,140 )141 except ValueError:136 self.fail('%s is not a valid integer' % value, param, ctx)142 self.fail(f"{value!r} is not a valid integer", param, ctx)143144 BASED_INT = BasedIntParamType()145140As you can see, a subclass needs to implement the :meth:`ParamType.convert`141method and optionally provide the :attr:`ParamType.name` attribute. The142latter can be used for documentation purposes.146The :attr:`~ParamType.name` attribute is optional and is used for147documentation. Call :meth:`~ParamType.fail` if conversion fails. The148``param`` and ``ctx`` arguments may be ``None`` in some cases such as149prompts.