⌨️

FastAPIの弟分?Typerを用いたCLIアプリケーション開発

2025/01/16に公開

Typerとは

公式ドキュメントを雑に訳すと、Typerはユーザーが使いやすく、開発者が作りやすい、CLIアプリケーションを開発するためのライブラリだそうです。

Typer is a library for building CLI applications that users will love using and developers will love creating. Based on Python type hints.

開発者目線の利点:エディタのコード補完等の機能を存分に活用することができる(タイプヒントの利用)。必要最小限のコードから始めることができ、複雑なアプリケーションにも対応。
ユーザー目線の利点:ヘルプの自動生成、シェル上での自動補完。

The key features are:

  • Intuitive to write: Great editor support. Completion everywhere. Less time debugging. Designed to be easy to use and learn. Less time reading docs.
  • Easy to use: It's easy to use for the final users. Automatic help, and automatic completion for all shells.
  • Short: Minimize code duplication. Multiple features from each parameter declaration. Fewer bugs.
  • Start simple: The simplest example adds only 2 lines of code to your app: 1 import, 1 function call.
  • Grow large: Grow in complexity as much as you want, create arbitrarily complex trees of commands and groups of subcommands, with options and arguments.
  • Run scripts: Typer includes a typer command/program that you can use to run scripts, automatically converting them to CLIs, even if they don't use Typer internally.

https://typer.tiangolo.com

(FastAPIの弟分らしい?使用感もFastAPIに近い)
https://fastapi.tiangolo.com/ja/#typer-the-fastapi-of-clis

実際にTyperを触ってみる

早速Typerを触ってみる。

Typeのインストール

shell
$ pip install typer

Typerで簡単なCLIアプリケーションの作成

公式ドキュメントのコードを引用。
FastAPIのように app = typer.Typer() でTyperインスタンスを作成し、コマンドとして実行したい関数にデコレータを適用するだけ。

main.py
import typer

app = typer.Typer()

@app.command()
def hello(name: str):
    print(f"Hello {name}")

@app.command()
def goodbye(name: str, formal: bool = False):
    if formal:
        print(f"Goodbye Ms. {name}. Have a good day.")
    else:
        print(f"Bye {name}!")

if __name__ == "__main__":
    app()

以下のようにコマンドを実行できる。

shell
$ python main.py hello World
Hello World

$ python main.py goodbye Mary --formal
Goodbye Ms. Mary. Have a good day.

各種コマンド

CLIから利用可能なコマンドやコマンドの引数を確認することができる。

  • 利用可能なコマンドの確認
shell
$ python main.py --help

 Usage: main.py [OPTIONS] COMMAND [ARGS]...                                                                                                         
                                                                                                                                                    
╭─ Options ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────╮
│ --install-completion          Install completion for the current shell.                                                                          │
│ --show-completion             Show completion for the current shell, to copy it or customize the installation.                                   │
│ --help                        Show this message and exit.                                                                                        │
╰──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────╯
╭─ Commands ───────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────╮
│ hello                                                                                                                                            │
│ goodbye                                                                                                                                          │
╰──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────╯
  • コマンドの引数を確認
shell
$ python main.py hello --help

 Usage: main.py hello [OPTIONS] NAME                                                                                                                
                                                                                                                                                    
╭─ Arguments ──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────╮
│ *    name      TEXT  [default: None] [required]                                                                                                  │
╰──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────╯
╭─ Options ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────╮
│ --help          Show this message and exit.                                                                                                      │
╰──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────╯

おわりに

本記事ではCLIアプリケーション開発のためのライブラリであるTyperを紹介しました。
TyperはFastAPI経験者であれば簡単に利用することができるため、既にAPI開発にFastAPIを利用している場合には、Typerは有望な選択肢になるかもしれません。ぜひお試しください!

Discussion