To do that, use the envvar parameter for typer.Argument():
importtyperfromtyping_extensionsimportAnnotateddefmain(name:Annotated[str,typer.Argument(envvar="AWESOME_NAME")]="World"):print(f"Hello Mr. {name}")if__name__=="__main__":typer.run(main)
Tip
Prefer to use the Annotated version if possible.
importtyperdefmain(name:str=typer.Argument("World",envvar="AWESOME_NAME")):print(f"Hello Mr. {name}")if__name__=="__main__":typer.run(main)
In this case, the CLI argumentname will have a default value of "World", but will also read any value passed to the environment variable AWESOME_NAME if no value is provided in the command line:
fast βπ¬ Check the helppython main.py --help Usage: main.py [OPTIONS] [NAME]
You are not restricted to a single environment variable, you can declare a list of environment variables that could be used to get a value if it was not passed in the command line:
importtyperfromtyping_extensionsimportAnnotateddefmain(name:Annotated[str,typer.Argument(envvar=["AWESOME_NAME","GOD_NAME"])]="World",):print(f"Hello Mr. {name}")if__name__=="__main__":typer.run(main)
Tip
Prefer to use the Annotated version if possible.
importtyperdefmain(name:str=typer.Argument("World",envvar=["AWESOME_NAME","GOD_NAME"])):print(f"Hello Mr. {name}")if__name__=="__main__":typer.run(main)
Check it:
fast βπ¬ Check the helppython main.py --help Usage: main.py [OPTIONS] [NAME]
By default, environment variables used will be shown in the help text, but you can disable them with show_envvar=False:
importtyperfromtyping_extensionsimportAnnotateddefmain(name:Annotated[str,typer.Argument(envvar="AWESOME_NAME",show_envvar=False)]="World",):print(f"Hello Mr. {name}")if__name__=="__main__":typer.run(main)
Tip
Prefer to use the Annotated version if possible.
importtyperdefmain(name:str=typer.Argument("World",envvar="AWESOME_NAME",show_envvar=False)):print(f"Hello Mr. {name}")if__name__=="__main__":typer.run(main)
Check it:
fast β//Check the helppython main.py --help π¬ It won't show the env varUsage: main.py [OPTIONS] [NAME]
Arguments: [NAME] [default: World]
Options: --help Show this message and exit.
π¬ But it will still be able to use itAWESOME_NAME=Wednesday python main.py Hello Mr. Wednesday