Replies: 1 comment
-
AFAIK, there is no way I can think of to directly inject a single object into the This is the solution I propose: from typing import Annotated
import typer
class EnvConfig:
def __init__(self, source_paths: list[str]):
self._source_paths = source_paths
def __len__(self):
return 1
def __iter__(self):
yield self
def parser(value: str) -> str:
return value
def callback(ctx: typer.Context, param: typer.CallbackParam, values: list[str]) -> EnvConfig:
return EnvConfig(values)
app = typer.Typer()
@app.command()
def main(env: Annotated[list[EnvConfig], typer.Option(parser=parser, callback=callback)]):
env = env[0]
assert isinstance(env, EnvConfig)
if __name__ == "__main__":
typer.run(main) I tried your snippet and I got |
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.
-
First Check
Commit to Help
Example Code
Description
So the above code successfully parses multiple string options into a single EnvConfig instance but it injects the parameter as a list with one element.
Is it somehow possible to tell typer to interpret the input as multi-valued and then parse it into a single instance and pass that as argument?
I already have it running with a group callback (there I add it as a list of string options to the callback, construct the EnvConfig in the callback and set the instance as ctx.obj. In a command I can then use a 'fake' option to inject it back in (if required). However this is an approach that only works if I actually have a group to use with the group callback and this is not always the case.
The original reason I got here is that I have multiple environments that can define where to find other available configurations or which actual configurations to use in the CLI. I already built some logic around this using the 'click_type' to inject the other configurations based on the base EnvConfig in the context on demand and that works pretty well for me.
An example for this would be to enable a set of VM configurations and be able to point it to different 1Password configurations to use:
mycli --env vm-set1 --env op-vault1 create-ssh-keys "vm-s1-foo"
mycli --env vm-set2 --env op-vault2 create-ssh-keys "vm-s2-bar"
The command would then look something like this
@app.command()
def create_ssh_keys(
env: Annotated[EnvConfig, typer.Option(click_type=from_context_param(EnvConfig), hidden=True, default_factory=lambda: True)],
vm_set_config: Annotated(VMSetConfig, from_env_config(VMSetConfig)),
op_vault_config: Annotated(OPVaultConfig, from_env_config(OPVaultConfig)),
vm_name: str
):
... code ...
Operating System
Linux
Operating System Details
No response
Typer Version
0.15.1
Python Version
Python 3.12.1
Additional Context
No response
Beta Was this translation helpful? Give feedback.
All reactions