Callable Types and Custom Actions
In fact, you can use any callable. Whatever the user gives you gets sent as the parameter to the callable. This gives some interesting possibilities. You could use the
ord function to get the ASCII value or Unicode code point of a character.
But don’t go crazy. Some things are better to be handled in your code rather than as side effects to your argument parser. For example, the reason the
store_true action exists instead of just using the
bool callable is because
bool treats empty strings as false and non-empty strings as true.
So your string containing
0 will not give the value you might have expected. That
open I mentioned earlier, it just feels icky to me. And that could only get worse, if you start using a file decoder of some sort. It will work, but the errors start to become opaque.
01:23 The user won’t be able to see the difference between a bad value for the argument and a good value that points to a file with bad contents. Generally, I recommend sticking to the more common cases and avoiding getting too fancy.
This is both because you have to be careful with corner cases and also for the readability of your code. Another developer coming along might not expect the namespace to contain an
open file, let alone a fully parsed one.
Before showing you how to write your own, I’m going to show you something slightly simpler, using the built-in
action class that doesn’t correspond to an
action string name. Instead of giving something like
store_true, you can give any class that inherits from
I’ll show you what that looks like in a second. The other thing I’ve done in this line is to use the
dest parameter. This parameter allows you to specify what the name of the variable in the namespace is. Since
try is a keyword in Python, if I attempted to use it as is, I’d get a
My action is going to add
"Bork, bork, bork!" to the string being stored. As such, I don’t want to handle multiple arguments. Single items only. On lines 6 and 7, I make sure that
nargs isn’t set.
Your method must use these same arguments or it won’t work. What you get passed in is the
parser instance, the namespace you’re modifying, the values from the command line, and any option strings. On line 12, I take whatever values I was given and add
"Bork, bork, bork!" to the end.
04:56 My script only takes a single argument, so to give it something with spaces in it, I need to surround it with quotes. The operating system uses space to distinguish between arguments sent to the script. By putting it in quotes, my entire sentence from Gonzo is considered as a single argument.
Become a Member to join the conversation.