How to get the value of the last expression using sys.last_value in Python?
Published on Aug. 22, 2023, 12:17 p.m.
To get the value of the last expression using sys.last_value
in Python, you can use the following code:
import sys
x = 5
y = 10
z = x + y # The value of z is 15
last_result = sys.last_value # The value of last_result is 15
The sys.last_value
attribute is used to retrieve the value of the last expression that was executed in the current interpreter session. Note that this only works if there was actually a value returned by the last expression; if the last expression had no return value (i.e. a print statement), sys.last_value
will be None
.
It’s worth noting that while sys.last_value
provides the last result, it does not provide context around it. Thus, if the last operation was not just z = x + y but, for instance, some arithmetic operation, it will not provide any information regarding the operands.