Python Forum

Full Version: When does Python detect Errors?
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hello, I am currently confused about the different times when errors are detected in Python...

First, for my understanding:
Python initially translates the written code into bytecode, and this time is called "compilation." Then, the code is interpreted line by line, which is the runtime. We cannot speak of a strict compilation like in Java in the case of Python. Have I understood everything correctly up to this point?

Now, for my next issue:
I don't quite understand when different errors are detected in Python.
For example, shouldn't a Syntax Error be detected during compilation? Because Python cannot translate grammatically incorrect code. However, my script states that Python recognizes Syntax Errors when the interpreter reaches the faulty line (and executes the code up to that point). Which one is correct?

As for static-semantic and dynamic-semantic errors, in my understanding, they should be detected during runtime. For instance, accessing an undefined variable does not involve a grammatical error, so the code can be translated without issues.

Thank you for any assistance!
All python code is "executed" when the file is "compiled". First the source is converted into bytecodes, then the bytecodes are executed to define classes and functions and assign variables in the global scope. Syntax errors that result in not being able to parse the source code are caught in the conversion stage. Syntax errors like "this needs to be an expression" are caught in the second stage. Due to the dynamic nature of python, runtime errors like NameErrors, and AttributeErrors cannot be detected at this time. Python doesn't know what kind of object a function argument will be until the function gets called.

You can use a static analysis tool like mypy to catch a lot of the errors that would be caught by a traditional compiler. Consistently using type annotations helps with static analysis, and many IDE's can use the type information to identify potential problems and provide better code completion suggestions.

There is no substitute for testing. Python has great unit testing tools to help you detect runtime errors.