Home > Mobile >  Python passing a method to another method
Python passing a method to another method

Time:03-08

What i'm trying to do is create a time polling method/mechanism, which as input recieves a method it needs to run inside the time loop (from other modules\classes and might or might not have input params itself) , exit condition (True/False/String/Int) and the timeout This is what i've created

def time_polling(polled_method,exit_condition,timer):
   elapsed_time = 0
   sleep_period = 10
   while elapsed_time<=int(timer):
      if polled_method == exit_condition:
         return True
      time.sleep(sleep_period)
      elapsed_time =sleep_period
   return False

the way i call it is like this :

timed_polling(lambda: validation_installation.ValidationInstallation.check_installed_product(),True,60)

The problem is that if i call the method without the lambda , then obviously the call is made inside the call command , with the lambda it seems that the method is not being called inside the timed_polling method. What am I missing?

CodePudding user response:

why so complex ? No need for lambda.

timed_polling(lambda: validation_installation.ValidationInstallation.check_installed_product(),True,60)

should be just

# note: no parentheses, pass function object itself
timed_polling(validation_installation.ValidationInstallation.check_installed_product,True,60)

then in the code this is wrong as polled_method is a method, and it needs to be called now so:

  if polled_method == exit_condition:
     return True

should be (added () to call it):

  if polled_method() == exit_condition:
     return True

else the method is not called

  • Related