[Python-Dev] PEP 389: argparse - new command line parsing module (original) (raw)

Steven D'Aprano steve at pearwood.info
Sun Oct 4 03:26:51 CEST 2009


On Sun, 4 Oct 2009 05:35:04 am André Malo wrote:

* Steven D'Aprano wrote: > You don't need a comment warning that you are catching SystemExit > because parseargs raises SystemExit, any more than you need a > comment saying that you are catching ValueError because some > function raises ValueError. The fact that you are catching an > exception implies that the function might raise that exception. A > comment like: > > "Catching SystemExit because parseargs() throws SystemExit on > parser errors." > > is up them with comments like this: > > x += 1 # Add 1 to x.

It's semantically different. You usually don't catch SystemExit directly, because you want your programs to be stopped.

Exactly -- so why catch it at all? But even if there is a good reason to catch it, there's still no reason to subclass SystemExit unless argparse wants to distinguish different types of fatal error, and allow code to catch some but not all. But frankly, if I'm having a hard time thinking of a reason to catch SystemExit, I'm having an even harder time thinking why you'd want to (say) catch SystemExitTooManyArguments but not SystemExitMissingArgument.

Additionally, a library exiting your program is badly designed, as it's unexpected.

It's not unexpected for an argument parser. Do you know any applications that run when given invalid arguments? As a general rule, what can the application do? Guess what you wanted?

Thatswhy such a comment is useful.

The comment doesn't tell you anything that wasn't obvious from the code. It is pointless.

Here's what I'd do: I'd subclass SystemExit in this case and raise the subclass from argparse.

In the following code snippet:

try: ns = argparse.parse_args() except SystemExit: ...

is there any confusion between SystemExit raised by parse_args and SystemExit raised by other components? What other components? If SystemExit was raised in that try block, where could it have come from other than parse_args?

Do you write comments like these?

try: value = mydict[key] except KeyError: # Catch KeyError raised by dict lookup ...

try: n = mylist.index(x) except ValueError: # Catch ValueError raised by mylist.index ...

Useless comments are worse than no comments, because useless comments waste the readers' time and they risk becoming out of sync with the code and turning into misleading comments.

That way all parties here should be satisifed.

No. It wastes the time of the argparse developer, it wastes the time of people learning argparse, it wastes the time of people who read the code and wonder what's the difference between SystemExit and ArgparseSystemExit. (Answer: there is no difference.)

-- Steven D'Aprano



More information about the Python-Dev mailing list