Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python exec() with an if statement

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?

like image 358
Quelklef Avatar asked Jan 24 '26 22:01

Quelklef


2 Answers

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).

like image 77
Greg Hewgill Avatar answered Jan 26 '26 11:01

Greg Hewgill


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")
like image 22
smci Avatar answered Jan 26 '26 11:01

smci