複数値を持つCLIオプション
異なる型の複数の値を受け取るCLIオプションも宣言できます。
値の数と型は任意に設定できますが、値の数は固定である必要があります。
これには、標準のPython `typing.Tuple`を使用します。
from typing import Tuple
import typer
from typing_extensions import Annotated
def main(user: Annotated[Tuple[str, int, bool], typer.Option()] = (None, None, None)):
username, coins, is_wizard = user
if not username:
print("No user provided")
raise typer.Abort()
print(f"The username {username} has {coins} coins")
if is_wizard:
print("And this user is a wizard!")
if __name__ == "__main__":
typer.run(main)
ヒント
可能な限り、`Annotated`バージョンを使用することをお勧めします。
from typing import Tuple
import typer
def main(user: Tuple[str, int, bool] = typer.Option((None, None, None))):
username, coins, is_wizard = user
if not username:
print("No user provided")
raise typer.Abort()
print(f"The username {username} has {coins} coins")
if is_wizard:
print("And this user is a wizard!")
if __name__ == "__main__":
typer.run(main)
内部型のそれぞれは、タプル内の各値の型を定義します。
つまり
user: Tuple[str, int, bool]
は、パラメータ`user`が3つの値のタプルであることを意味します。
- 最初の値は`str`です。
- 2番目の値は`int`です。
- 3番目の値は`bool`です。
後で、次のようにします。
username, coins, is_wizard = user
ご覧になったことがない場合、これは`user`が3つの値を持つタプルであり、各値を新しい変数に代入していることを意味します。
- タプル`user`の最初の値(`str`)は変数`username`に代入されます。
- タプル`user`の2番目の値(`int`)は変数`coins`に代入されます。
- タプル`user`の3番目の値(`bool`)は変数`is_wizard`に代入されます。
したがって、これ
username, coins, is_wizard = user
はこれと同等です。
username = user[0]
coins = user[1]
is_wizard = user[2]
ヒント
デフォルトは`(None, None, None)`のタプルであることに注意してください。
Clickはサポートしていないため、ここでデフォルトとして`None`を単純に使うことはできません。
確認¶
それでは、ターミナルでこれがどのように動作するかを見てみましょう。
// check the help
$ python main.py --help
// Notice the <TEXT INTEGER BOOLEAN>
Usage: main.py [OPTIONS]
Options:
--user <TEXT INTEGER BOOLEAN>...
--help Show this message and exit.
// Now try it
$ python main.py --user Camila 50 yes
The username Camila has 50 coins
And this user is a wizard!
// With other values
$ python main.py --user Morty 3 no
The username Morty has 3 coins
// Try with invalid values (not enough)
$ python main.py --user Camila 50
Error: Option '--user' requires 3 arguments