-
-
Notifications
You must be signed in to change notification settings - Fork 656
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Need feature to share options or arguments between commands #405
Comments
@allinhtml One way to accomplish this is to have a module level object, a dataclass instance or a dict etc, to hold the state, and a callback to set it. from typing import Optional, List
import typer
import os
app = typer.Typer(add_completion=False)
state = {}
@app.callback()
def _main(
debug: bool = typer.Option(False, "--debug", help="If set print debug messages"),
output_dir: str = typer.Option(os.getcwd(), help="The output directory"),
):
state["debug"] = debug
state["output_dir"] = output_dir
@app.command()
def start(
flows: Optional[List[str]] = typer.Option(None, "--flow", "-f"),
):
typer.echo(f"Debug mode: {state['debug']}")
typer.echo(f"Output Dir: {state['output_dir']}")
typer.echo(f"start flows: {flows}")
@app.command()
def stop():
typer.echo(f"Debug mode: {state['debug']}")
typer.echo(f"Output Dir: {state['output_dir']}")
typer.echo("STOP!")
@app.command()
def clean():
typer.echo(f"Debug mode: {state['debug']}")
typer.echo(f"Output Dir: {state['output_dir']}")
typer.echo("STOP!")
if __name__ == "__main__":
app() with debug: ❯ python issue.py --debug --output-dir GitHub start
Debug mode: True
Output Dir: GitHub
start flows: () without: ❯ python issue.py --output-dir GitHub clean
Debug mode: False
Output Dir: GitHub
STOP! :) |
Is there a way to create common CLI options such, that they are configurable on the sub command level instead of on the command level? e.g.
So that the command could be given as follows: python issue.py clean --output-dir GitHub |
I need this feature, too. I posted some code related to working around this, here. The workarounds are "OK" but not great. |
You can use the Context object no? import typer
app = typer.Typer()
@app.callback()
def main_app(
ctx: typer.Context,
verbose: Optional[bool] = typer.Option(None, help="Enable verbose mode.")
):
obj = ctx.ensure_object(dict)
obj["verbose"] = verbose
@app.command()
def test(ctx: typer.Context):
obj = ctx.ensure_object(dict)
print(obj) see https://typer.tiangolo.com/tutorial/commands/context/ |
Will have to check that out, hopefully this weekend. |
Not a perfect solution, but what I've been doing is defining the
|
Actually, this is a good solution. Listing the input arguments in a function's definition (signature) makes code that is easy to read and understand. Defining typer |
I'm using something similar to the previous example to share options. Here's a contrived example:
Note that the only difference between the I'm trying to figure out some way I can use a single
Anyone got any ideas how I might implement this? |
I tried this:
Sadly, this throws a couple of flake8 syntax errors:
|
Following works for me : ❯ cat test.py from datetime import datetime
from types import SimpleNamespace
from typing import Annotated, Optional
import typer
app = typer.Typer()
def make_date_option(help="Enter a date"):
return Annotated[
Optional[datetime],
typer.Option(
formats=["%Y-%m-%d"],
help=help,
),
]
@app.command()
def main(
start_date: make_date_option(help='Start') = None,
end_date: make_date_option(help='End') = None,
):
print(f"{start_date} - {end_date}") and ❯ typer test.py run --start-date '2010-01-01' --end-date '2011-02-02'
2010-01-01 00:00:00 - 2011-02-02 00:00:00 I think you have a comma left-over in the end of the |
Good spot, but I think that's a copy/paste error and not the source of the F722 error. Re-visiting, I've found that this code runs just fine (with the extra comma removed), but the Syntastic flake8 check still throws the error. Using the power of google, I found this solution: https://stackoverflow.com/a/73235243 Adding SimpleNamesapce to the mix, I ended up with this final code:
In a real project, |
I have many shared options, as per your |
Only you can decide what's "worth the effort" |
I don't understand why this only forks with |
I guess because it needs to be a function, and cannot be a variable/constant. |
First Check
Commit to Help
Example Code
Description
How can we easily add common options into multiple commands like debug or output_directory?
Related question - #153 - But this is not working as expected. Help section don't show message properly as commented here.
Operating System
Linux, Windows, macOS
Operating System Details
No response
Typer Version
ALL
Python Version
ALL
Additional Context
No response
The text was updated successfully, but these errors were encountered: