Skip to content

@pass_meta_key decorator #1739

@eshaan7

Description

@eshaan7

Idea Proposal:

As a click's plugin developer, we use the click.Context.meta dictionary to store any state. So IMHO, click could provide another decorator: @click.pass_metavar(key="foo") similar to @click.pass_obj.

Example implementation:

def pass_metavar(key: str):
    """Similar to :func:`click.pass_obj`,
    this passes the ctx.meta[key] variable instead as the first argument.
    """

    def decorator(f):
            @click.pass_context
            def new_func(ctx: click.Context, *args, **kwargs):
                var = ctx.meta[key]
                return ctx.invoke(f, var, *args, **kwargs)

        return update_wrapper(new_func, f)
    
    return decorator

Example usage:

@click.pass_metavar(key="foo")
def bar(var):
    click.echo(var)

I think this would be beneficial for click's plugin developers and naturally anyone building a complex CLI app which requires using the click.Context.meta to store state.

If you like the idea, I will be glad to raise a PR for it asap.

Metadata

Metadata

Assignees

Labels

No labels
No labels

Type

No type

Projects

No projects

Milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions