CLIパラメータの種類入門
CLIオプションとCLI引数にはいくつかのデータ型を使用でき、データ検証要件を追加することもできます。
データ変換¶
ある型でCLIパラメータを宣言すると、**Typer**はコマンドラインで受信したデータをそのデータ型に変換します。
例えば
import typer
def main(name: str, age: int = 20, height_meters: float = 1.89, female: bool = True):
print(f"NAME is {name}, of type: {type(name)}")
print(f"--age is {age}, of type: {type(age)}")
print(f"--height-meters is {height_meters}, of type: {type(height_meters)}")
print(f"--female is {female}, of type: {type(female)}")
if __name__ == "__main__":
typer.run(main)
この例では、CLI引数NAME
で受信した値はstr
として扱われます。
CLIオプション--age
の値はint
に変換され、--height-meters
はfloat
に変換されます。
そして、female
はbool
型のCLIオプションなので、**Typer**はそれを「フラグ」--female
と対応する--no-female
に変換します。
そして、それはこのように見えます
$ python main.py --help
// Notice how --age is an INTEGER and --height-meters is a FLOAT
Usage: main.py [OPTIONS] NAME
Arguments:
NAME [required]
Options:
--age INTEGER [default: 20]
--height-meters FLOAT [default: 1.89]
--female / --no-female [default: True]
--help Show this message and exit.
// Call it with CLI parameters
$ python main.py Camila --age 15 --height-meters 1.70 --female
// All the data has the correct Python type
NAME is Camila, of type: class 'str'
--age is 15, of type: class 'int'
--height-meters is 1.7, of type: class 'float'
--female is True, of type: class 'bool'
// And if you pass an incorrect type
$ python main.py Camila --age 15.3
Usage: main.py [OPTIONS] NAME
Try "main.py --help" for help.
Error: Invalid value for '--age': '15.3' is not a valid integer
// Because 15.3 is not an INTEGER (it's a float)
次はこれ¶
具体的な型と検証については、次のセクションで説明します…
技術詳細
次のセクションで説明するすべての型は、Clickのパラメータ型によって内部的に処理されます。