Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p><code>SyntaxError</code> is diagnosed by the Python compiler as it compiles -- you're presumably trying to "catch" it from code that's being compiled as part of the same module (e.g., that's what you're doing in your code sample), so of course it won't work -- your "catching" code hasn't been compiled yet (because compilation has terminated unsuccessfully) so it can't catch anything.</p> <p>You need to ensure the code that might have a syntax error gets compiled <em>later</em> than the catching code -- either put it in a separate module that you import in the <code>try</code> clause, or in a string you <code>compile</code> with the built-in by that name (you can later execute the bytecode resulting from the <code>compile</code> call, if it terminates successfully).</p> <p>Neither possibility looks good for your purposes, I think. I suspect that using two separate modules (and probably picking between them depending on the "does this compile" check, but a version check sounds much cleaner to me) is the only "clean" solution, unfortunately.</p> <p><strong>Edit</strong>: here's how to microbenchmark try/except against version checks:</p> <pre><code>$ python2.4 -mtimeit 'try: compile("with x: pass", "", "exec") except SyntaxError: x=1 else: x=2' 100000 loops, best of 3: 10.8 usec per loop $ python2.6 -mtimeit 'try: compile("with x: pass", "", "exec") except SyntaxError: x=1 else: x=2' 10000 loops, best of 3: 40.5 usec per loop $ python2.4 -mtimeit -s'import sys' 'if sys.version&gt;="2.5": x=2 else: x=1' 1000000 loops, best of 3: 0.221 usec per loop $ python2.6 -mtimeit -s'import sys' 'if sys.version&gt;="2.5": x=2 else: x=1' 10000000 loops, best of 3: 0.156 usec per loop </code></pre> <p>As you see, the version I consider cleaner is <code>10.8 / 0.221</code>, almost 50 times faster, on 2.4, and <code>40.5 / 0.156</code>, almost 260 times faster, on 2.6. In general (with rare exceptions), the clean (i.e., "pythonic") approach will turn out to be the better optimized one in Python -- often, at least part of the reason can be that Python core developers focus on facilitating and encouraging the use of constructs they like, rather than that of constructs they dislike.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload