As a long time Python developer, I would recommend that anybody learning the language to NOT pay any attention to this article. It is careless to omit any sort of error checking, command-line options, etc., in a command-line tool. At least look at the built-in module argparse.
I don't really think this short script is wrong. What can really happen? If you don't pass something which is an int in sys.argv[2:4], you'll get a ValueError. If you don't pass something which is not a correct operation in sys.argv[1], you'll get a KeyError. I agree it is not "explicit error handling", but for a simple program like that I'm not really sure you really want to add so much logic for error checking, I mean, it is a simple program, so keep it simple.
The question of the pertinence of this article and of a linking in reddit is more important. Should we link on reddit a blog post everytime we discover a trivial feature of a language ? (Look mum, I know how to print a value...). This code is so trivial that it may be compacted in one line (changing a bit the behavior, I agree):
(Interested readers may notice a minor difference in behavior between my two version, the why is let as an exercise for the reader).
Version with rough error checking:
import operator
import sys
try:
operation = getattr(operator, sys.argv[1])
except (AttributeError, IndexError):
sys.exit("You must provide a correct operation as first argument. Availables ones are {}.".format(', '.join(dir(operator))))
try:
operand = list(map(int, sys.argv[2:]))
except ValueError:
sys.exit("You must provid integer arguments after your operation.")
try:
print(operation(*operand))
except TypeError:
sys.exit("Your operation takes more or less integer arguments.")
I think error checking here is too overkill for such a simple program ;)
I thought the same about error checking, otherwise, I pretend to build a more complex script so was good to know better libraries to do that.
About the relevance, for me it values a post, I have seen people searching stuffs like that in several languages. About reddit, I don't know, I started to participate now and I have seen links like this one, maybe they are the exceptions. Don't forget that it's managed by the community , up and down votes should be used for this reason.
Google gives really good results when you look for "command line parsing python" or "command line arguments python"...
For the community stuff, I agree that the community will vote, but unfortunately some communities contains so much noise that users stop to use them. By the way, there is other posts on your blog which should be posted on reddit, but that one was really too much trivial.
5
u/EmmEff Jun 18 '13
As a long time Python developer, I would recommend that anybody learning the language to NOT pay any attention to this article. It is careless to omit any sort of error checking, command-line options, etc., in a command-line tool. At least look at the built-in module argparse.