Skip to content Skip to sidebar Skip to footer

Dealing With Context Classes In Python 2.4

I'm trying to use the python-daemon module. It supplies the daemon.DaemonContext class to properly daemonize a script. Although I'm primarily targeting Python 2.6+, I'd like to mai

Solution 1:

SyntaxError 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.

You need to ensure the code that might have a syntax error gets compiled later than the catching code -- either put it in a separate module that you import in the try clause, or in a string you compile with the built-in by that name (you can later execute the bytecode resulting from the compile call, if it terminates successfully).

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.

Edit: here's how to microbenchmark try/except against version checks:

$ python2.4 -mtimeit 'try:
  compile("with x: pass", "", "exec")
except SyntaxError: x=1else: x=2'
100000 loops, best of 3: 10.8 usec per loop
$ python2.6 -mtimeit 'try:
  compile("with x: pass", "", "exec")
except SyntaxError: x=1else: x=2'
10000 loops, best of 3: 40.5 usec per loop

$ python2.4 -mtimeit -s'import sys' 'if sys.version>="2.5": x=2else: x=1'
1000000 loops, best of 3: 0.221 usec per loop
$ python2.6 -mtimeit -s'import sys' 'if sys.version>="2.5": x=2else: x=1'
10000000 loops, best of 3: 0.156 usec per loop

As you see, the version I consider cleaner is 10.8 / 0.221, almost 50 times faster, on 2.4, and 40.5 / 0.156, 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.

Post a Comment for "Dealing With Context Classes In Python 2.4"