How would I do the following:
>>> new=exec('i=100;2 if i > 4 else 3')
>>> repr(new)
'None'
I want to get 2
:
>>> i=100
>>> 2 if i>4 else 3
2
I can do this with eval
, as long as there isn't an assignment:
>>> new=eval('2 if i>4 else 3')
>>> new
2
In other words, how to execute a string of code (with an assignment, not just eval
) and get the last part?
Here is a related question from ~5 years ago: not sure if the answers still apply though, or anything has changed since then: How do I get the return value when using Python exec on the code object of a function?.