Is it possible to dynamically generate commands in Python Click

2024/10/14 13:22:56

I'm trying to generate click commands from a configuration file. Essentially, this pattern:

import click@click.group()
def main():passcommands = ['foo', 'bar', 'baz']
for c in commands:def _f():print("I am the '{}' command".format(c))_f = main.command(name=c)(_f)if __name__ == '__main__':main()

The --help text looks good:

Usage: test_click.py [OPTIONS] COMMAND [ARGS]...Options:--help  Show this message and exit.Commands:barbazfoo

However all of the commands seem to route to the last one that gets generated:

$ ./test_click.py foo
I am the 'baz' command
$ ./test_click.py bar
I am the 'baz' command
$ ./test_click.py baz
I am the 'baz' command

Is what I'm attempting actually possible?

Answer

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()
def main():passcommands = ['foo', 'bar', 'baz']def bind_function(name, c):def func():print("I am the '{}' command".format(c))func.__name__ = namereturn funcfor 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.

https://en.xdnf.cn/q/69407.html

Related Q&A

Different accuracy between python keras and keras in R

I build a image classification model in R by keras for R.Got about 98% accuracy, while got terrible accuracy in python.Keras version for R is 2.1.3, and 2.1.5 in pythonfollowing is the R model code:mod…

Named Entity Recognition in aspect-opinion extraction using dependency rule matching

Using Spacy, I extract aspect-opinion pairs from a text, based on the grammar rules that I defined. Rules are based on POS tags and dependency tags, which is obtained by token.pos_ and token.dep_. Belo…

Python Socket : AttributeError: __exit__

I try to run example from : https://docs.python.org/3/library/socketserver.html#socketserver-tcpserver-example in my laptop but it didnt work.Server :import socketserverclass MyTCPHandler(socketserver.…

How to save pygame Surface as an image to memory (and not to disk)

I am developing a time-critical app on a Raspberry PI, and I need to send an image over the wire. When my image is captured, I am doing like this:# pygame.camera.Camera captures images as a Surface pyg…

Plotting Precision-Recall curve when using cross-validation in scikit-learn

Im using cross-validation to evaluate the performance of a classifier with scikit-learn and I want to plot the Precision-Recall curve. I found an example on scikit-learn`s website to plot the PR curve …

The SECRET_KEY setting must not be empty || Available at Settings.py

I tried to find this bug, but dont know how to solve it.I kept getting error message "The SECRET_KEY setting must not be empty." when executing populate_rango.pyI have checked on settings.py …

Pandas: Applying Lambda to Multiple Data Frames

Im trying to figure out how to apply a lambda function to multiple dataframes simultaneously, without first merging the data frames together. I am working with large data sets (>60MM records) and I …

scipy.minimize - TypeError: numpy.float64 object is not callable running

Running the scipy.minimize function "I get TypeError: numpy.float64 object is not callable". Specifically during the execution of:.../scipy/optimize/optimize.py", line 292, in function_w…

Flask, not all arguments converted during string formatting

Try to create a register page for my app. I am using Flask framework and MySQL db from pythonanywhere.com. @app.route(/register/, methods=["GET","POST"]) def register_page(): try:f…

No module named objc

Im trying to use cocoa-python with Xcode but it always calls up the error:Traceback (most recent call last):File "main.py", line 10, in <module>import objc ImportError: No module named …