typer icon indicating copy to clipboard operation
typer copied to clipboard

[FEATURE] Reusable options

Open flupke opened this issue 4 years ago • 3 comments

Is your feature request related to a problem

There is no way currently in typer to reuse options and their processing.

With click this is something you'd do with decorators:

import functools
import click


def foobar_options(func):

    @click.option("--foo")
    @click.option("--bar")
    @functools.wraps(func)
    def wrapper(foo, bar, **kwargs):
        process_foo(foo)
        # Pass bar to the decorated command
        return func(bar=bar, **kwargs)

    return wrapper


@click.command()
@foobar_options
def command(bar):
    process_bar(bar)

The solution you would like

Options definitions could be packed in dataclasses:

import dataclasses
import typer


app = typer.Typer()


@dataclasses.dataclass
class FooBarOptions:
    foo: str = typer.Option(None)
    bar: str = typer.Option(None)


@app.command()
def command(foobar_options: FooBarOptions):
    process_foo(foobar_options.foo)
    process_bar(foobar_options.bar)

While not exactly equivalent to the decorator approach (you can't factorize the processing), I like this too. What do you think?

flupke avatar Apr 09 '21 10:04 flupke

I am trying to do the same thing. I had it working in click and being able to do this in Typer would ideal. I have a slight difference in that I want to pass in extra parameters instead of just reusing but essentially the same use case.

Would love any feedback if anyone has any on how to go about this.

mmcenti avatar Jun 25 '21 15:06 mmcenti

Nice feature. Any updates on this? I know tyro is able to achieve this?

luocfprime avatar Jan 11 '25 04:01 luocfprime

The solution with dataclasses is the same as requested in #154

YuriiMotov avatar Sep 17 '25 09:09 YuriiMotov