Rename python click argument - python

I have this chunk of code:
import click
#click.option('--delete_thing', help="Delete some things columns.", default=False)
def cmd_do_this(delete_thing=False):
print "I deleted the thing."
I would like to rename the option variable in --delete-thing. But python does not allow dashes in variable names. Is there a way to write this kind of code?
import click
#click.option('--delete-thing', help="Delete some things columns.", default=False, store_variable=delete_thing)
def cmd_do_this(delete_thing=False):
print "I deleted the thing."
So delete_thing will be set to the value of delete-thing

By default, click will intelligently map intra-option commandline hyphens to underscores so your code should work as-is. This is used in the click documentation, e.g., in the Choice example. If --delete-thing is intended to be a boolean option, you may also want to make it a boolean argument.

As gbe's answer says, click will automatically convert - in the cli parameters to _ for the python function parameters.
But you can also explicitly name the python variable to whatever you want. In this example, it converts --delete-thing to new_var_name:
import click
#click.command()
#click.option('--delete-thing', 'new_var_name')
def cmd_do_this(new_var_name):
print(f"I deleted the thing: {new_var_name}")

Related

How to view argument names in pycharm debugger console?

Let's say I need to view the argument names in the editor, it's usually done with cmd/ctrl + p and here's the view:
However when I try the same in the debugger console, I only get *args, **kwargs
How to change this behavior to be able to see the actual argument names?
script path/Module name
Click the list to select a type of target to run. Then, in the corresponding field, specify the path to the Python script or the module name to be executed.

Select Directory with Python

I want to select 5 images with Python so that I can use these imges in my python program. I tried to do this with QFileDialog() (PyQt5) but I only succeed to single select a file.
And how to select a folder is also not really comprehensive.
I just want to select 5 images and select a folder so that I can save files in that folder. But it seems to be not so easy to do that.
I really like Python because its so easy but PyQt5 makes me everytime I use it just aggressive, all other libraries are just nice and easy to understand.
Maybe there is a good alternative to pyqt? tkinter maybe?
thanks.
In order to select a folder you can use this code:
widget = QWidget()
dialog = QFileDialog(
widget, "Select Directory of the Desired Files", os.path.curdir
)
dialog.setFileMode(QFileDialog.DirectoryOnly)
Qt supplies a bunch of static methods to get standardized file dialogs, two of them already satisfy your needs: getOpenFileNames() (stress on the final "s") and getExistingDirectory().
The first will return a list of absolute paths of selected file[s], the last will return the selected directory.
I know that reading the official documentation might be a bit overwhelming if you don't know anything about C++ (they are explained in detail, though), but they're not as hard as one could think.
Every function is listed in a very simple way:
returned_type : function_name(arguments) [const -> you can usually ignore this]
The returned_type is the type of the value the function is expected to return. In "c++ slang", void is the same as return (or return None or no return at all, as Python implicitly returns None if no other value/object is returned at the end of a function), if the type is a QString it's automatically converted to a Python str, while qreal is the same as Python's floats,. This is very important for "private" functions (methods), which are internally used by Qt: if you are subclassing and want to override a private method of a Qt class, you have to return the type Qt expects. You could theoretically ignore the returned_type for public functions if you know what you're doing, but it's usually better to stick with the original type.
There are some small "exceptions" that require some consideration. In some cases Qt expects some argument that will be modified within the function and would normally return whether the function was successful or not, while in Python it might return the reference to the argument (sorry, I can't remember them right now). Some other functions return a tuple instead of a single value, and that's the case of some static QFileDialog functions such as getOpenFileName[s] which return both the selected file[s] and the selected filter.

Python Click command names

I'm using the click package for creating a command line tool. However, I would like to have a 'list' command. For example:
#click.command
#click.option(help='list...')
def list():
# do stuff here
Is there another way in click to pass in a command name other than having it as the function name? I don't want this function to shadow python's built in list. I've looked through the documentation and can't really find anything about command names -- I've read up on command aliases but that doesn't seem to help this problem. Or do I not need to worry about list being shadowed since it's being wrapped by the click decorator? Thanks in advance.
You can provide the name argument when you use the command decorator. Once you've done that, you can name your function whatever you want:
#click.command(name='list')
def list_command():
pass
See the Click documentation for details.

List/inspect the instance variables (self.xxx) while using pudb

I am trying to debug a python application using pudb, everything is fine and good except that it's not displaying the instance variables (which we access with self.xxx). It just displays 1 variable called self. And it's of the original class type.
Even if I tell it to show after calling str(self), it still only displays the object information.
If you see the code has created many variables like self.parser, self.groups and I am not able to view/inspect any of them.
Is there a way to view all the instance variables of the current class while debugging using pudb?
This is the expected behaviour, and has nothing to do with your debugger: you only have one name, self.
To see its contents you can use dir(self).
See inspect complex variable in python debugger, like pudb
The short way: Highlight the variable and press backslash \ to toggle between the "Expanded" view of a variable in the variable inspection panel.
In this case we would just highlight self, and press \, which is just the Python variable representing the instance of the class.
Alternatively, press ENTER to open the "Variable Inspection Options" menu where at the bottom you can see the "Expanded" option.

Python: tell my IDE what type an object is

When I write a function in Python (v2.7), I very often have a type in mind for one of the arguments. I'm working with the unbelievably brilliant pandas library at the movemement, so my arguments are often 'intended' to be pandas.DataFrames.
In my favorite IDE (Spyder), when you type a period . a list of methods appear. Also, when you type the opening parenthesis of a method, the docstring appears in a little window.
But for these things to work, the IDE has to know what type a variable is. But of course, it never does. Am I missing something obvious about how to write Pythonic code (I've read Python Is Not Java but it doesn't mention this IDE autocomplete issue.
Any thoughts?
I don't know if it works in Spyder, but many completion engines (e.g. Jedi) also support assertions to tell them what type a variable is. For example:
def foo(param):
assert isinstance(param, str)
# now param will be considered a str
param.|capitalize
center
count
decode
...
Actually I use IntelliJ idea ( aka pyCharm ) and they offer multiple ways to specify variable types:
1. Specify Simple Variable
Very simple: Just add a comment with the type information behind the definition. From now on Pycharm supports autcompletition! e.g.:
def route():
json = request.get_json() # type: dict
Source: https://www.jetbrains.com/help/pycharm/type-hinting-in-pycharm.html
2. Specify Parameter:
Add three quote signs after the beginning of a method and the idea will autocomplete a docstring, as in the following example:
Source: https://www.jetbrains.com/help/pycharm/using-docstrings-to-specify-types.html
(Currently on my mobile, going to make it pretty later)
If you're using Python 3, you can use function annotations. As an example:
#typechecked
def greet(name: str, age: int) -> str:
print("Hello {0}, you are {1} years old".format(name, age))
I don't use Spyder, but I would assume there's a way for it to read the annotations and act appropriately.
I don't know whether Spyder reads docstrings, but PyDev does:
http://pydev.org/manual_adv_type_hints.html
So you can document the expected type in the docstring, e.g. as in:
def test(arg):
'type arg: str'
arg.<hit tab>
And you'll get the according string tab completion.
Similarly you can document the return-type of your functions, so that you can get tab-completion on foo for foo = someFunction().
At the same time, docstrings make auto-generated documention much more helpful.
The problem is with the dynamic features of Python, I use Spyder and I've used a lot more of python IDEs (PyCharm, IDLE, WingIDE, PyDev, ...) and ALL of them have the problem you stated here. So, when I want code completion for help I just instantiate the variable to the type I want and then type ".", for example: suppose you know your var df will be a DataFrame in some piece of code, you can do this df = DataFrame() and for now on the code completion should work for you just do not forget to delete (or comment) the line df = DataFrame() when you finish editing the code.

Categories