LoginSignup
0
0

[Python] typerのbool型オプションにTrue/Falseを与えて使いたい

Posted at

はじめに

よく忘れるのでメモ。

typerのオプションをbool型にすると、argparseのaction="store_true"みたいな挙動になります(厳密には違う)が、単純にTrueまたはFalseを与えたいことがあるかもしれません。

tmp.py
import typer

def main(
    input_text: str = typer.Argument(...),
    print_flag: bool = typer.Option(False)
):
    if print_flag:
        print(input_text)

if __name__ == "__main__":
    typer.run(main)
% python tmp.py test --print-flag
test

% python tmp.py test --print-flag False
Usage: tmp.py [OPTIONS] INPUT_TEXT
Try 'tmp.py --help' for help.

Error: Got unexpected extra argument (False)

is_flag=Falseにするだけ

typer.Optionis_flag=Falseを指定するだけです。

print_flag: bool = typer.Option(False, is_flag=False)
% python tmp.py test --print-flag False

% python tmp.py test --print-flag True 
test

% python tmp.py test --print-flag     
Error: Option '--print-flag' requires an argument.

おわりに

argparseに別れを告げてtyperに移行しています。大変つかいやすいのでおすすめ。まだ情報が少なくて「typer オプション」と検索するとシビックTYPE-Rが出て思わず笑うなどしますが。

以下の記事がよくまとまっています。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0