Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can python handle unevaluated expression arguments?

Tags:

python

I want to pass a statement to a python function. This statement should only be executed after I do some other stuff in the function. By default, python evaluates the statement and then passes its result as the parameter.

Is there any way to change this behavior?

The only way I have found is to wrap my statement in a function and then pass the function.

like image 688
nsheff Avatar asked Jun 24 '26 19:06

nsheff


1 Answers

Most Python programmers agree that passing the function would be the natural, safest, and most maintainable approach to this problem:

In [ 2]: add_one = lambda a: a+1

In [ 3]: def my_func2(a, statement):
   ....:     print a
   ....:     a = statement(a)
   ....:     print a
   ....:     

In [ 4]: a
Out[ 4]: 9

In [ 5]: my_func2(a, add_one)
9
10

But there is an exec statement that provides an unnatural, insecure and potentially confusing alternative:

In [ 6]: def my_func(a, statement):
   ....:     print a
   ....:     exec(statement)
   ....:     print a
   ....:     

In [ 7]: a = 9

In [ 8]: my_func(a, 'a += 1')
9
10

In all honesty, I can't see why you would do it this way, though.

like image 111
xnx Avatar answered Jun 26 '26 10:06

xnx



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!