Skip to content

[FEATURE] Reusable options #264

Description

@flupke

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?

Metadata

Metadata

Assignees

No one assigned

    Labels

    featureNew feature, enhancement or request

    Type

    No type

    Fields

    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions