Imagine I had some function like this:
def func(condition):
while condition:
pass
Is there any way that I can pass a comparison as condition, for example func(50 > x)
, but then instead of it executing as while False
(x would be some value under 50), it does while 50 > x
(I want to do something like x += 1, so the loop stops eventually)? I want to do this because I will have the same function in two different situations, and each of them has a while loop, but the condition has to be different from one another. What I did until now is pass another argument into func
, so def func(condition,situation)
, and then I would do while 50 > x if situation == 1 else True
. However, I believe the way I am trying to do it, would be faster, because in the way I have been doing it thus far, after each loop, not only would 50 > x
or True
have to be evaluated again, but also if situation == 1
.
This is about what I want to do
limit = 50
start = 0
def func(condition)
while condition:
pass
start += 1
# once I need the function like this, once I need it with True, so the loop runs forever in that case
func(limit > start)
func(True)
Maybe by passing a comparison function and the desired parameters? Something like this:
comparison_a = lambda x, y: x > y
comparison_b = lambda x, y: x <= y
(assuming your second condition is something like x <= y
) This creates two lambda (for simplification) functions that perform the desired comparison with the parameters x
and y
Then you create your function as:
def func(comparison, start, limit):
while comparison(start, limit):
start += 1
And call it as:
limit = 50
start = 30
func(comparison_a, 50, 30)
Optionally, you could use the operator
module, which implements python operators as functions. For the greater than
operator you have operator.gt
. As an example:
import operator
limit = 50
start = 30
func(operator.gt, 50, 30)
While I would advise against dynamic parameters like this, you could use the built-in eval
method, which takes a string of Python and evaluates it inline.
def func(condition: String):
while eval(condition):
pass
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.