Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

selenium python: what is 'lambda' in webdriverwait.until statements

I'm learning selenium webdriver with python and came across 'lambda' in following line of code. The author did not explain the use of lambda here:

search_button = WebDriverWait(self.driver, 10).until(lambda s:s.find_element_by_name("btnG"))
search_button.click()  

I've read about lambda and it says lambda creates functions on the fly and some say its used to return expression. So now I'm confused and not sure exactly what difference does it make here.

like image 650
Mohit Avatar asked Oct 19 '22 17:10

Mohit


1 Answers

In python functions are objects so you can pass them as parameters to other functions. The only thing is if you pass a function with () you call that function at the same time. So it's possible to pass functions which do not take any arguments so it can be called inside the function you passing it to later on. But if you need to pass parameters to the function while you are passing function itself you need to wrap it up in lambda so that it's called only when it's needed.

Edit

To answer the question how it gets s value. If you look into the source here doctoring explains it all:

"""Calls the method provided with the driver as an argument until the return value is not False."""

Actual code is self explanatory as well:

    def until(self, method, message=''):
    screen = None
    stacktrace = None

    end_time = time.time() + self._timeout
    while True:
        try:
            value = method(self._driver)
            if value:
                return value
        except self._ignored_exceptions as exc:
            screen = getattr(exc, 'screen', None)
            stacktrace = getattr(exc, 'stacktrace', None)
        time.sleep(self._poll)
        if time.time() > end_time:
            break
    raise TimeoutException(message, screen, stacktrace)
like image 114
T.Chmelevskij Avatar answered Oct 22 '22 14:10

T.Chmelevskij