variable declaration

Alex Martelli aleaxit at yahoo.com
Tue Feb 8 12:34:10 EST 2005


top <alexandre.tp at gmail.com> wrote:

> Alex Martelli wrote:
> [snip]
> > I disagree: compile time is when the compiler is running (for
> example,
> > the compiler is the component which diagnoses syntax errors, while
> other
> > errors are diagnosed ``at runtime'').
> [snip]
> 
> That thing about syntax errors is news to me. I thought they were
> caught at runtime, since you can catch them as exceptions, as in:
> 
> try: prijnt projnt
> except SyntaxError: print "See, it gets caught"

Nope:

kallisti:~/cb alex$ cat a.py
try: prijnt projnt
except SyntaxError: print "See, it gets caught"

kallisti:~/cb alex$ python a.py 
  File "a.py", line 1
    try: prijnt projnt
                     ^
SyntaxError: invalid syntax
kallisti:~/cb alex$ 

> If this happens at compile-time, I'd like to know how.

You can catch SyntaxError when it happens (e.g) on an explicit call to
the built-in function ``compile'', or, say:

>>> try: import a
... except SyntaxError: print "caught!"
... 
caught!

Here, the compilation of a.py (which has the error, see the cat above)
happens AFTER the try/except itself has been compiled, and while the try
clause is executing (compiling happens as part of import of a .py unless
the .pyc file is already there & updated); so the exception handler can
of course catch the exception.


Alex



More information about the Python-list mailing list