Is It Possible To Dynamically Generate Commands In Python Click
I'm trying to generate click commands from a configuration file. Essentially, this pattern: import click @click.group() def main(): pass commands = ['foo', 'bar', 'baz'] for
Solution 1:
The problem is with functional scope of python. When you create the function _f
it is using c
which has a higher scope than the function. So it will not be retained when you invoke the function. (_f
is invoked when you call main)
By the time you invoke main
the loop is complete and c will always hold the last value of the loop - which is baz
The solution is to attach the value c
to function using its own scope.
import click
@click.group()defmain():
pass
commands = ['foo', 'bar', 'baz']
defbind_function(name, c):
deffunc():
print("I am the '{}' command".format(c))
func.__name__ = name
return func
for c in commands:
f = bind_function('_f', c)
_f = main.command(name=c)(f)
if __name__ == '__main__':
main()
The bind_function
also allows you to name your functions differently if required.
Solution 2:
You should use function that creates another function for your command, here the example
import click
commands = ['foo', 'bar', 'baz']
@click.group()defmain():
passdefcreate_func(val):
deff():
print("I am the '{}' command".format(val))
return f
for c in commands:
main.command(name=c)(create_func(c))
if __name__ == '__main__':
main()
Post a Comment for "Is It Possible To Dynamically Generate Commands In Python Click"