Calmcode - typer: callbacks

Callbacks

1 2 3 4 5 6 7 8 9 10

Arguments in typer are increadibly flexible. Not only can they provide help text, they can also be used to attach other useful properties. In this video we've seen how you can attach callbacks to it.

Here's the program at the end of the video.

import typer
from typing import List
from pathlib import Path

app = typer.Typer(name="demo", add_completion=False, help="This is a demo app.")


def check_file_exists(paths):
    for p in paths:
        if not p.exists():
            print(f"The path you've supplied {p} does not exist.")
            raise typer.Exit(code=1)
    return paths

@app.command()
def word_count(paths: List[Path] = typer.Argument(...,
                                                help="The file to count the words in.",
                                                callback=check_file_exists)):
    """Counts the number of words in a file"""
    for p in paths:
        texts = p.read_text().split("\n")
        n_words = len(set(w for t in texts for w in t.split(" ")))
        print(f"In total there are {n_words} words in {p}.")

if __name__ == "__main__":
    app()

You should now be able to confirm that the command is able to accept multiple files but that it will also exit if one of the files does not exist.