Typing stubs for click - a command line interface creation kit for Python
Rich type system for validating and converting command-line inputs including built-in types for common patterns like file paths, choices, numeric ranges, and custom type creation.
Fundamental types for common data validation patterns.
class ParamType:
name: str
is_composite: bool
envvar_list_splitter: str | None
def convert(self, value: str, param: Parameter | None, ctx: Context | None) -> Any:
"""
Convert string input to the appropriate type.
Parameters:
- value: Input string value
- param: Parameter being processed
- ctx: Current context
Returns:
Converted value
Raises:
BadParameter: If conversion fails
"""
def fail(self, message: str, param: Parameter | None = None, ctx: Context | None = None) -> NoReturn:
"""
Fail with a parameter error.
Parameters:
- message: Error message
- param: Parameter that failed
- ctx: Current context
"""Built-in Type Constants:
BOOL: BoolParamType # Boolean type (true/false, yes/no, 1/0)
INT: IntParamType # Integer type
FLOAT: FloatParamType # Float type
STRING: StringParamType # String type (default)
UUID: UUIDParameterType # UUID type
UNPROCESSED: UnprocessedParamType # Raw string typeRestricts input to a predefined set of choices with optional case sensitivity.
class Choice(ParamType):
choices: Iterable[str]
case_sensitive: bool
def __init__(self, choices: Iterable[str], case_sensitive: bool = True) -> None:
"""
Choice parameter type for restricted input values.
Parameters:
- choices: Allowed choice values
- case_sensitive: Whether matching is case sensitive
Usage:
@click.option('--format', type=click.Choice(['json', 'xml', 'yaml']))
@click.option('--level', type=click.Choice(['DEBUG', 'INFO', 'ERROR'], case_sensitive=False))
"""Validates numeric input within specified ranges with optional clamping.
class IntRange(IntParamType):
min: int | None
max: int | None
clamp: bool
def __init__(self, min: int | None = None, max: int | None = None, clamp: bool = False) -> None:
"""
Integer range parameter type.
Parameters:
- min: Minimum allowed value
- max: Maximum allowed value
- clamp: Clamp values to range instead of failing
Usage:
@click.option('--port', type=click.IntRange(1, 65535))
@click.option('--threads', type=click.IntRange(min=1, max=32, clamp=True))
"""
class FloatRange(FloatParamType):
min: float | None
max: float | None
clamp: bool
def __init__(self, min: float | None = None, max: float | None = None, clamp: bool = False) -> None:
"""
Float range parameter type.
Parameters:
- min: Minimum allowed value
- max: Maximum allowed value
- clamp: Clamp values to range instead of failing
Usage:
@click.option('--ratio', type=click.FloatRange(0.0, 1.0))
@click.option('--temperature', type=click.FloatRange(min=-273.15))
"""Validates file and directory paths with existence checking and permission validation.
class Path(ParamType):
exists: bool
file_okay: bool
dir_okay: bool
writable: bool
readable: bool
resolve_path: bool
allow_dash: bool
type: Type[str] | Type[bytes] | None
def __init__(
self,
exists: bool = False,
file_okay: bool = True,
dir_okay: bool = True,
writable: bool = False,
readable: bool = True,
resolve_path: bool = False,
allow_dash: bool = False,
path_type: Type[str] | Type[bytes] | None = None,
) -> None:
"""
Path parameter type for file system paths.
Parameters:
- exists: Path must exist
- file_okay: Accept file paths
- dir_okay: Accept directory paths
- writable: Path must be writable
- readable: Path must be readable
- resolve_path: Resolve to absolute path
- allow_dash: Allow '-' for stdin/stdout
- path_type: Return type (str or bytes)
Usage:
@click.option('--input', type=click.Path(exists=True, readable=True))
@click.option('--output', type=click.Path(writable=True))
@click.option('--config-dir', type=click.Path(exists=True, file_okay=False))
"""
def convert(self, value: str, param: Parameter | None, ctx: Context | None) -> str | bytes: ...Handles file opening with mode, encoding, and lazy loading options.
class File(ParamType):
mode: str
encoding: str | None
errors: str | None
lazy: bool | None
atomic: bool
def __init__(
self,
mode: str = "r",
encoding: str | None = None,
errors: str | None = None,
lazy: bool | None = None,
atomic: bool = False,
) -> None:
"""
File parameter type for file objects.
Parameters:
- mode: File open mode ('r', 'w', 'rb', etc.)
- encoding: Text encoding
- errors: Error handling ('strict', 'ignore', 'replace')
- lazy: Lazy file opening
- atomic: Atomic file operations
Usage:
@click.option('--input', type=click.File('r'))
@click.option('--output', type=click.File('w', encoding='utf-8'))
@click.option('--data', type=click.File('rb'))
"""
def convert(self, value: str, param: Parameter | None, ctx: Context | None) -> IO[Any]: ...Parses datetime strings with configurable formats.
class DateTime(ParamType):
formats: Sequence[str]
def __init__(self, formats: Sequence[str] | None = None) -> None:
"""
DateTime parameter type for date/time parsing.
Parameters:
- formats: List of strptime format strings to try
Default formats:
- '%Y-%m-%d'
- '%Y-%m-%dT%H:%M:%S'
- '%Y-%m-%d %H:%M:%S'
Usage:
@click.option('--date', type=click.DateTime())
@click.option('--timestamp', type=click.DateTime(['%Y-%m-%d %H:%M:%S']))
"""
def convert(self, value: str, param: Parameter | None, ctx: Context | None) -> datetime.datetime: ...Combines multiple parameter types into composite tuples.
class Tuple(CompositeParamType):
types: list[ParamType]
arity: int
def __init__(self, types: Iterable[Any]) -> None:
"""
Tuple parameter type for composite values.
Parameters:
- types: List of types for tuple elements
Usage:
@click.option('--point', type=click.Tuple([int, int]))
@click.option('--coord', type=click.Tuple([float, float, str]))
"""
def convert(self, value: str, param: Parameter | None, ctx: Context | None) -> tuple: ...Additional specialized parameter types.
class UUIDParameterType(ParamType):
def convert(self, value: str, param: Parameter | None, ctx: Context | None) -> uuid.UUID:
"""
UUID parameter type.
Usage:
@click.option('--id', type=click.UUID)
"""
class UnprocessedParamType(ParamType):
"""
Unprocessed parameter type that passes values through unchanged.
Usage:
@click.option('--raw', type=click.UNPROCESSED)
"""
class FuncParamType(ParamType):
func: Callable[[str | None], Any]
def __init__(self, func: Callable[[str | None], Any]) -> None:
"""
Function-based parameter type for custom conversion.
Parameters:
- func: Conversion function
Usage:
def parse_coordinates(value):
if value is None:
return None
try:
x, y = value.split(',')
return (float(x), float(y))
except ValueError:
raise click.BadParameter('Coordinates must be in format "x,y"')
@click.option('--coords', type=click.FuncParamType(parse_coordinates))
"""
def convert(self, value: str, param: Parameter | None, ctx: Context | None) -> Any: ...Helper functions for working with parameter types.
def convert_type(ty: Any | None, default: Any | None = None) -> ParamType:
"""
Convert various type specifications to ParamType instances.
Parameters:
- ty: Type specification (type, ParamType, tuple, callable)
- default: Default value for type inference
Returns:
ParamType instance
Usage:
# These are equivalent:
click.option('--count', type=int)
click.option('--count', type=click.INT)
click.option('--count', type=click.convert_type(int))
"""Base classes for creating custom parameter types.
class CompositeParamType(ParamType):
arity: int
"""
Base class for parameter types that consume multiple arguments.
"""
class BoolParamType(ParamType):
"""
Boolean parameter type accepting various true/false representations.
Accepts: true/false, yes/no, 1/0, on/off (case insensitive)
"""
class StringParamType(ParamType):
"""
String parameter type (default for all parameters).
"""
class IntParamType(ParamType):
"""
Integer parameter type with validation.
"""
class FloatParamType(ParamType):
"""
Float parameter type with validation.
"""Custom Type Example:
class EmailType(click.ParamType):
name = 'email'
def convert(self, value, param, ctx):
if value is None:
return None
if '@' not in value:
self.fail(f'{value} is not a valid email address', param, ctx)
return value.lower()
# Usage
@click.option('--email', type=EmailType())
def register(email):
click.echo(f'Registering {email}')Pre-defined type instances for common parameter types, providing convenient shortcuts.
BOOL: BoolParamType
"""Boolean parameter type constant."""
FLOAT: FloatParamType
"""Float parameter type constant."""
INT: IntParamType
"""Integer parameter type constant."""
STRING: StringParamType
"""String parameter type constant."""
UNPROCESSED: UnprocessedParamType
"""Unprocessed parameter type constant (passes value as-is)."""
UUID: UUIDParameterType
"""UUID parameter type constant."""Usage with Type Constants:
# Using type constants instead of classes
@click.option('--count', type=click.INT)
@click.option('--ratio', type=click.FLOAT)
@click.option('--enabled', type=click.BOOL)
@click.option('--user-id', type=click.UUID)
def process(count, ratio, enabled, user_id):
click.echo(f"Count: {count} ({type(count)})")
click.echo(f"Ratio: {ratio} ({type(ratio)})")
click.echo(f"Enabled: {enabled} ({type(enabled)})")
click.echo(f"User ID: {user_id} ({type(user_id)})")
# Equivalent to:
@click.option('--count', type=int)
@click.option('--ratio', type=float)
@click.option('--enabled', type=bool)
@click.option('--user-id', type=click.types.UUIDParameterType())
def process_equivalent(count, ratio, enabled, user_id):
# Same functionality
passInstall with Tessl CLI
npx tessl i tessl/pypi-types-click