May-31-2022, 08:43 PM
(This post was last modified: May-31-2022, 08:51 PM by Gribouillis.)
(May-31-2022, 08:37 PM)anata2047 Wrote: How does this actually is implementedPython converts the code to an intermediate language named «bytecode». By using the
dis
module, one can examine this bytecode. Here is how python compiles the above conditional expression. It is apparent in the bytecode that the test in the middle is executed first. Of course, if x and y are not defined, an error will result.>>> import dis >>> dis.dis("a = x + y if x * y > 2 else x - 1") 1 0 LOAD_NAME 0 (x) 2 LOAD_NAME 1 (y) 4 BINARY_MULTIPLY 6 LOAD_CONST 0 (2) 8 COMPARE_OP 4 (>) 10 POP_JUMP_IF_FALSE 20 12 LOAD_NAME 0 (x) 14 LOAD_NAME 1 (y) 16 BINARY_ADD 18 JUMP_FORWARD 6 (to 26) >> 20 LOAD_NAME 0 (x) 22 LOAD_CONST 1 (1) 24 BINARY_SUBTRACT >> 26 STORE_NAME 2 (a) 28 LOAD_CONST 2 (None) 30 RETURN_VALUE >>>For details about the syntax of Python and how it works, I strongly recommend reading The Python language reference.