Replies: 1 comment
-
Yes, there is a way to only allow parameters initialized from environment variables leveraging Click's Solution: import typer
from click.core import ParameterSource
from typing import Annotated
def allow_only_env_var(ctx: typer.Context, param: typer.CallbackParam, value: str) -> str:
if ctx.get_parameter_source(param.name) != ParameterSource.ENVIRONMENT:
raise typer.BadParameter("only allowed as env var.")
return value
def main(name: Annotated[str, typer.Option(envvar="NAME", callback=allow_only_env_var)]):
print(f"Hello {name}")
if __name__ == "__main__":
typer.run(main) Behavior: $ python cli.py
Usage: cli.py [OPTIONS]
Try 'cli.py --help' for help.
╭─ Error ────────────────────────────────────╮
│ Missing option '--name' (env var: 'NAME'). │
╰────────────────────────────────────────────╯ $ python cli.py --name FOO
Usage: cli.py [OPTIONS]
Try 'cli.py --help' for help.
╭─ Error ────────────────────────────────────────────╮
│ Invalid value for '--name' (env var: 'NAME'): only │
│ allowed as an env var. │
╰────────────────────────────────────────────────────╯ $ NAME=BAR python cli.py --name FOO
Usage: cli.py [OPTIONS]
Try 'cli.py --help' for help.
╭─ Error ────────────────────────────────────────────╮
│ Invalid value for '--name' (env var: 'NAME'): only │
│ allowed as an env var. │
╰────────────────────────────────────────────────────╯ $ NAME=BAR python cli.py
Hello BAR |
Beta Was this translation helpful? Give feedback.
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
-
Hello,
I have a app that use threads/processes under the hood, so any initialized variables passed from args is not propagated/saved in the newly created process. However, ENV vars are accessible from there.
I know that ENV vars are a alternative way. But can they be the ONLY way to define arguments?
Operating System
Linux
Operating System Details
No response
Typer Version
0.15.1
Python Version
3.12.8
Additional Context
No response
Beta Was this translation helpful? Give feedback.
All reactions