I'm trying to find a way to exec() an if statement.
So, for example:
exampleCode = "if 0 < 1:"
exec(exampleCode)
print("Zero is less than one")
Now, obviously this isn't possible with exec(). But is it with something similar?
Something else that would work would be:
exampleCode = "if 0 < 1:"
exampleCode
print("Zero is less than one")
Again, this isn't possible, because variables cannot be code.
So, again, is there something else that may work?
You can do this, sort of, with eval:
exampleCode = "0 < 1"
if eval(exampleCode):
print("Zero is less than one")
...but it's unclear what the benefit is of doing this (that is, there's something you're not showing us that motivates your question).
Use a lambda (an anonymous function). We can pass an arbitrary lambda which allows dynamically evaluating a condition in the scope in which it is evaluated:
# 1) A lambda with 0 args; this is silly because it will always evluate to a constant
cond_0args = lambda: 0 < 1
# <function <lambda> at 0x1084ffc80>
# 2) A lambda with 2 args:
cond = lambda x, y: x<y
# ... you could of course have a lambda with 3 args or whatever
#cond = lambda x, y, z: some_expression_involving_x_y_z
if cond_0args():
print("Zero is less than one")
or, more sensibly:
if cond(0,1):
print("Zero is less than one")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With