Parameter Types — Click Documentation (8.2.x)

# Parameter Types

When the parameter type is set using `type`, Click will leverage the type to make your life easier, for example adding data to your help pages. Most examples are done with options, but types are available to options and arguments.

## Built-in Types Examples

### Choice

Sometimes, you want to have a parameter be a choice of a list of values. In that case you can use `Choice` type. It can be instantiated with a list of valid values. The originally passed choice will be returned, not the str passed on the command line. Token normalization functions and `case_sensitive=False` can cause the two to be different but still match. `Choice.normalize_choice()` for more info.

Example:

    import enum

    class HashType(enum.Enum):
        MD5 = 'MD5'
        SHA1 = 'SHA1'

    @click.command()
    @click.option('--hash-type',
                  type=click.Choice(HashType, case_sensitive=False))
    def digest(hash_type: HashType):
        click.echo(hash_type)

What it looks like:

    $ digest --hash-type=MD5
    HashType.MD5

    $ digest --hash-type=md5
    HashType.MD5

    $ digest --hash-type=foo
    Usage: digest [OPTIONS]
    Try 'digest --help' for help.

    Error: Invalid value for '--hash-type': 'foo' is not one of 'md5', 'sha1'.

    $ digest --help
    Usage: digest [OPTIONS]

    Options:
      --hash-type [md5|sha1]
      --help                  Show this message and exit.

Since version 8.2.0 any iterable may be passed to `Choice`, here an `Enum` is used which will result in all enum values to be valid choices.

Choices work with options that have `multiple=True`. If a `default` value is given with `multiple=True`, it should be a list or tuple of valid choices.

Choices should be unique after normalization, see `Choice.normalize_choice()` for more info.

Changelog

Changed in version 7.1: The resulting value from an option will always be one of the originally passed choices regardless of `case_sensitive`.

### Int and Float Ranges

The `IntRange` type extends the `INT` type to ensure the value is contained in the given range. The `FloatRange` type does the same for `FLOAT`.

If `min` or `max` is omitted, that side is unbounded. Any value in that direction is accepted. By default, both bounds are closed, which means the boundary value is included in the accepted range. `min_open` and `max_open` can be used to exclude that boundary from the range.

If `clamp` mode is enabled, a value that is outside the range is set to the boundary instead of failing. For example, the range `0, 5` would return `5` for the value `10`, or `0` for the value `-1`. When using `FloatRange`, `clamp` can only be enabled if both bounds are closed (the default).

    @click.command()
    @click.option("--count", type=click.IntRange(0, 20, clamp=True))
    @click.option("--digit", type=click.IntRange(0, 9))
    def repeat(count, digit):
        click.echo(str(digit) * count)

    $ repeat --count=100 --digit=5
    55555555555555555555
    $ repeat --count=6 --digit=12
    Usage: repeat [OPTIONS]
    Try 'repeat --help' for help.

    Error: Invalid value for '--digit': 12 is not in the range 0<=x<=9.

## Built-in Types Listing

The supported parameter Types are:

- `str` / `click.STRING`: The default parameter type which indicates unicode strings.

- `int` / `click.INT`: A parameter that only accepts integers.

- `float` / `click.FLOAT`: A parameter that only accepts floating point values.

- `bool` / `click.BOOL`: A parameter that accepts boolean values. This is automatically used for boolean flags. The string values “1”, “true”, “t”, “yes”, “y”, and “on” convert to `True`. “0”, “false”, “f”, “no”, “n”, and “off” convert to `False`.

- `click.UUID`: A parameter that accepts UUID values. This is not automatically guessed but represented as `uuid.UUID`.

- class click.Choice(choices, case_sensitive=True)

    The choice type allows a value to be checked against a fixed set of supported values.

    You may pass any iterable value which will be converted to a tuple and thus will only be iterated once.

    The resulting value will always be one of the originally passed choices. See `normalize_choice()` for more info on the mapping of strings to choices. See Choice for an example.

    Parameters:

      - case_sensitive (bool) – Set to false to make choices case insensitive. Defaults to true.

      - choices (Sequence[ParamTypeValue])

    Changed in version 8.2.0: Non-`str` `choices` are now supported. It can additionally be any iterable. Before you were not recommended to pass anything but a list or tuple.

    Added in version 8.2.0: Choice normalization can be overridden via `normalize_choice()`.

- class click.DateTime(formats=None)

    The DateTime type converts date strings into `datetime` objects.

    The format strings which are checked are configurable, but default to some common (non-timezone aware) ISO 8601 formats.

    When specifying DateTime formats, you should only pass a list or a tuple. Other iterables, like generators, may lead to surprising results.

    The format strings are processed using `datetime.strptime`, and this consequently defines the format strings which are allowed.

    Parsing is tried using each format, in order, and the first format which parses successfully is used.

    Parameters:

      formats (cabc.Sequence[str] | None) – A list or tuple of date format strings, in the order in which they should be tried. Defaults to `'%Y-%m-%d'`, `'%Y-%m-%dT%H:%M:%S'`, `'%Y-%m-%d %H:%M:%S'`.

- class click.File(mode='r', encoding=None, errors='strict', lazy=None, atomic=False)

    Declares a parameter to be a file for reading or writing. The file is automatically closed once the context tears down (after the command finished working).

    Files can be opened for reading or writing. The special value `-` indicates stdin or stdout depending on the mode.

    By default, the file is opened for reading text data, but it can also be opened in binary mode or for writing. The encoding parameter can be used to force a specific encoding.

    The `lazy` flag controls if the file should be opened immediately or upon first IO. The default is to be non-lazy for standard input and output streams as well as files opened for reading, `lazy` otherwise. When opening a file lazily for reading, it is still opened temporarily for validation, but will not be held open until first IO. lazy is mainly useful when opening for writing to avoid creating the file until it is needed.

    Files can also be opened atomically in which case all writes go into a separate file in the same folder and upon completion the file will be moved over to the original location. This is useful if a file regularly read by other users is modified.

    See File Arguments for more information.

    Changelog

    Changed in version 2.0: Added the `atomic` parameter.

    Parameters:

      - mode (str)

      - encoding (str | None)

      - errors (str | None)

      - lazy (bool | None)

      - atomic (bool)

- class click.FloatRange(min=None, max=None, min_open=False, max_open=False, clamp=False)

    Restrict a `click.FLOAT` value to a range of accepted values. See Int and Float Ranges.

    If `min` or `max` are not passed, any value is accepted in that direction. If `min_open` or `max_open` are enabled, the corresponding boundary is not included in the range.

    If `clamp` is enabled, a value outside the range is clamped to the boundary instead of failing. This is not supported if either boundary is marked `open`.

    Changelog

    Changed in version 8.0: Added the `min_open` and `max_open` parameters.

    Parameters:

      - min (float | None)

      - max (float | None)

      - min_open (bool)

      - max_open (bool)

      - clamp (bool)

- class click.IntRange(min=None, max=None, min_open=False, max_open=False, clamp=False)

    Restrict an `click.INT` value to a range of accepted values. See Int and Float Ranges.

    If `min` or `max` are not passed, any value is accepted in that direction. If `min_open` or `max_open` are enabled, the corresponding boundary is not included in the range.

    If `clamp` is enabled, a value outside the range is clamped to the boundary instead of failing.

    Changelog

    Changed in version 8.0: Added the `min_open` and `max_open` parameters.

    Parameters:

      - min (float | None)

      - max (float | None)

      - min_open (bool)

      - max_open (bool)

      - clamp (bool)

- class click.Path(exists=False, file_okay=True, dir_okay=True, writable=False, readable=True, resolve_path=False, allow_dash=False, path_type=None, executable=False)

    The `Path` type is similar to the `File` type, but returns the filename instead of an open file. Various checks can be enabled to validate the type of file and permissions.

    Parameters:

      - exists (bool) – The file or directory needs to exist for the value to be valid. If this is not set to `True`, and the file does not exist, then all further checks are silently skipped.

      - file_okay (bool) – Allow a file as a value.

      - dir_okay (bool) – Allow a directory as a value.

      - readable (bool) – if true, a readable check is performed.

      - writable (bool) – if true, a writable check is performed.

      - executable (bool) – if true, an executable check is performed.

      - resolve_path (bool) – Make the value absolute and resolve any symlinks. A `~` is not expanded, as this is supposed to be done by the shell only.

      - allow_dash (bool) – Allow a single dash as a value, which indicates a standard stream (but does not open it). Use `open_file()` to handle opening this value.

      - path_type (type[t.Any] | None) – Convert the incoming path value to this type. If `None`, keep Python’s default, which is `str`. Useful to convert to `pathlib.Path`.

    Changelog

    Changed in version 8.1: Added the `executable` parameter.

    Changed in version 8.0: Allow passing `path_type=pathlib.Path`.

    Changed in version 6.0: Added the `allow_dash` parameter.

## How to Implement Custom Types

To implement a custom type, you need to subclass the `ParamType` class. For simple cases, passing a Python function that fails with a `ValueError` is also supported, though discouraged. Override the `convert()` method to convert the value from a string to the correct type.

The following code implements an integer type that accepts hex and octal numbers in addition to normal integers, and converts them into regular integers.

    import click

    class BasedIntParamType(click.ParamType):
        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 ValueError:
                self.fail(f"{value!r} is not a valid integer", param, ctx)

    BASED_INT = BasedIntParamType()

The `name` attribute is optional and is used for documentation. Call `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.