Victor Stinner writes: > the idea), but I don't understand the purpose of adding a new syntax > doing exactly the same than try/except: > > > with trap(OSError) as cm: > > os.unlink('missing.txt') > > if cm.exc: > > do_something() > > Nobody noticed that this can be written: > > try: > os.unlink('missing.txt') > except OSError as err: > # do something with err
A couple of people did, and it was pointed out that "with trap ... if" allows intervening statements that are *not* in the "with" suite, while all of the statements between "try" and "except" must be part of the "try" suite. The actual equivalent would be try: os.unlink('missing.txt') except OSError as err: pass # unhandled statements may go here if err: # do something with err This is really horrible. > ?? What happened with the Zen Principle "There should be one-- and > preferably only one --obvious way to do it." AIUI, the justification for this feature goes something like this: 1. It is fast and effective to use a try ... except block to catch and ignore an exception, but it's awkward and ugly, which may deter people from catching those exceptions. This is much nicer. 2. The "attractive nuisance" argument against the nicer syntax is probably a fallacy: cargo cult programmers benefit as much as Raymond's students from the correct single-line-suite usage. On the other hand, nicer syntax may make it easier to wean the cargo cult programmers from multi-statement try suites, and there's little evidence that the nicer syntax would actually encourage them to use more multi-statement suites. 3. As for the *several* Zen principles this feature violates, we really should encourage people to "do something appropriate" with exceptions, instead of try: main() except: print("You REALLY SCREWED UP this time, didn't you!", file=sys.stderr) sys.exit(errors.PEBKAC) but encouraging robust programming is hard: exception handling is just plain awkward if you do it in any generality. We hope "with ignore()" can help in one frequently encountered, easily understood, use case. _______________________________________________ Python-Dev mailing list Python-Dev@python.org https://mail.python.org/mailman/listinfo/python-dev Unsubscribe: https://mail.python.org/mailman/options/python-dev/archive%40mail-archive.com