Search code examples
pythoncompilationinterpreter

Compiler Python, why are some wrong things overlooked?


I wrote a Python routine with a mistake in it: false instead of False. However, it was not discovered at compilation. The program had to run until this line to notify the wrongdoing.

Why is it so? What in the Python interpreter/compiler things make it work so?

Do you have some reference?


Solution

  • Due to Python's dynamic nature, it is impossible to detect undefined names at compile time. Only the syntax is checked; if the syntax is fine, the compiler generates the bytecode, and Python starts to execute the code.

    In the given example, you will get a reference to a global name false. Only when the bytecode interpreter tries to actually access this global name, you will get an error.

    To illustrate, here is an example. Do you think the following code executes fine?

    globals()["snyfr".decode("rot13")] = 17
    x = false
    

    It actually does, since the first line dynamically generates a variable named false.