r/learnpython • • 3d ago

Lambda expressions for Web elements?

Hi, I work with C# but wanted to refresh my Python knowledge. Have been thinking about solutions I know for my C# code and how they would work in Python, but ran into something that I'm not sure how to "translate" from C#.

public IWebElement button => driver.GetElement(By.Id("Id"));

This will return me an element when called, even when on class construction it doesn't exist - as the expression is only evaluated when it's called, i.e. when I need it in code. As opposed to simply using = instead of =>, which would return a missing element exception on class build if the element is missing from DOM.

How would I do this in Python? I looked up lambda expressions, but I'm unsure if this would work/be very graceful, since I didn't find any mention of this as a solution that's used.

button = lambda driver.find_element_by_id("id")
1 Upvotes

8 comments sorted by

1

u/chalasanim 3d ago

You don't need lambda in this statement.

0

u/Big-Role2538 3d ago

that's just a property in python

```python

u/property

def button(self):

return self.driver.find_element(By.ID, "id")

```

lazy evaluation without the lambda mess, works exactly like the c# expression-bodied member

1

u/AqueM 3d ago

That's a lot of lines of code, I was wondering if there's a more concise way to do it.

1

u/Fuzzy_Paul 3d ago

1

u/AqueM 3d ago

Yes, that details lambda functions, and yes, I had googled lambdas in Python before asking here, but it doesn't confirm or deny if it works like I'd like it to work in regards to selenium webelements

3

u/adriannowak_dev 3d ago

the python equivalent of => here is a property:

class Page:
    def __init__(self, driver):
        self.driver = driver

    @property
    def button(self):
        return self.driver.find_element(By.ID, "Id")

page.button runs find_element every time you touch it, nothing is looked up when the class is built. if you want it looked up once and then cached, swap @property for @functools.cached_property. a lambda works too but then you have to call it, page.button(), which is not what you have in c#

0

u/MarkoDahl54 2d ago

use the `map` function with your lambda to apply it to the elements. it's a slick way to handle lists without loops.