File and Path Error Management
Typer provides a robust system for managing files and paths by extending Click's validation logic and integrating it with Python's type hinting system. This implementation ensures that command-line arguments and options representing files or paths are validated before they reach your function, reducing boilerplate error handling.
Path Validation and TyperPath
When you annotate a parameter with pathlib.Path, Typer automatically uses the TyperPath class (a subclass of click.Path) to handle validation. The configuration for this validation is stored in ParameterInfo, which is the base class for typer.Option and typer.Argument.
Validation Constraints
You can configure specific constraints for a path using the parameters in typer.Option or typer.Argument. These are mapped directly to TyperPath in typer/main.py:
exists: IfTrue, the path must already exist.file_okay: IfFalse, the path cannot be a file.dir_okay: IfFalse, the path cannot be a directory.writable: IfTrue, the path must be writable.readable: IfTrue, the path must be readable.resolve_path: IfTrue, the path will be resolved to its absolute form.
In typer/main.py, the get_click_type function detects the Path annotation and instantiates TyperPath:
# From typer/main.py
elif (
annotation == Path
or parameter_info.allow_dash
or parameter_info.path_type
or parameter_info.resolve_path
):
return TyperPath(
exists=parameter_info.exists,
file_okay=parameter_info.file_okay,
dir_okay=parameter_info.dir_okay,
writable=parameter_info.writable,
readable=parameter_info.readable,
resolve_path=parameter_info.resolve_path,
allow_dash=parameter_info.allow_dash,
path_type=parameter_info.path_type,
)
Autocompletion Compatibility
TyperPath specifically overrides Click's shell_complete method to return an empty list. This is a design choice in Typer to ensure that its own internal autocompletion system handles path completion correctly without interference from Click's default behavior.
# From typer/models.py
class TyperPath(click.Path):
# Overwrite Click's behaviour to be compatible with Typer's autocompletion system
def shell_complete(
self, ctx: click.Context, param: click.Parameter, incomplete: str
) -> list[click.shell_completion.CompletionItem]:
"""Return an empty list so that the autocompletion functionality
will work properly from the commandline.
"""
return []
File Handling with Type Hints
Typer provides specialized type hints in typer.models that tell the framework to open a file and pass the file-like object directly to your function.
Text Files
FileText: Defaults to read mode (mode="r").FileTextWrite: Defaults to write mode (mode="w").
These classes inherit from io.TextIOWrapper. When used in an annotation, Typer configures a click.File type with the appropriate mode:
# From docs_src/parameter_types/file/tutorial001_an_py310.py
@app.command()
def main(config: Annotated[typer.FileText, typer.Option()]):
for line in config:
print(f"Config line: {line}")
Binary Files
For binary data, Typer provides:
FileBinaryRead: Inherits fromio.BufferedReader, defaults tomode="rb".FileBinaryWrite: Inherits fromio.BufferedWriter, defaults tomode="wb".
Strict Error Management
A critical aspect of Typer's file management is how it handles encoding and access errors.
Strict Encoding
In ParameterInfo, the errors parameter defaults to "strict". This means that if a file is opened with an encoding that cannot handle certain characters, or if the input file does not match the specified encoding, Typer (via Click) will raise a validation error rather than silently failing or producing corrupted data.
# From typer/models.py
class ParameterInfo:
def __init__(
self,
# ...
# File
mode: str | None = None,
encoding: str | None = None,
errors: str | None = "strict",
# ...
):
self.errors = errors
# ...
Automatic Error Reporting
When a validation constraint (like exists=True) is violated, Typer relies on Click's underlying error handling to provide user-friendly messages. For example, if a user provides a path that does not exist for a parameter configured with exists=True, the application will exit with a message similar to:
Error: Invalid value for '--config': Path 'non_existent.txt' does not exist.
This management is handled during the conversion phase in get_click_type, where the metadata from ParameterInfo is used to construct the validator that Click executes before your command function is ever called.