I have a case where I'd like to run a common function (check_upgrade()
) for most of my click commands, but there are a few cases where I don't want to run it. Rather than relying on developers to remember to add a decorator or function call to explicitly run this check, I'd prefer to instead run it by default and then have a decorator that one can add (e.g. @bypass_upgrade_check
) for commands where check_upgrade()
should not run.
I was hoping for something like:
class State(object):
def __init__(self):
self.bypass_upgrade_check = False
pass_state = click.make_pass_decorator(State, ensure=True)
def bypass_upgrade_check(func):
@pass_state
def wrapper(state, *args, **kwargs):
state.bypass_upgrade_check = True
func(*args, **kwargs)
return wrapper
@click.group()
@pass_state
def common(state):
if not state.bypass_upgrade_check:
check_upgrade()
@common.command()
def cmd1():
# check_upgrade() runs here
pass
@bypass_upgrade_check
@common.command()
def cmd2():
# don't run check_upgrade() here
pass
But this doesn't work. It doesn't actually ever call the bypass_upgrade_check()
function.
Is there a way to decorate a command in such a way that I can modify the state before the group code runs? Or another method altogether that accomplishes this?
To keep track of which commands bypass the upgrade check, I suggest that in the bypass marking decorator you store that state on the
click.Command
object. Then if you pass theclick.Context
to your group, you can then look at the command object to see if it is marked to allow skipping upgrade like:Code:
Test Code:
Results: