How to improve this code?

Dave Angel davea at ieee.org
Tue Sep 15 18:52:45 CEST 2009


Oltmans wrote:
> On Sep 15, 1:13 pm, Hendrik van Rooyen <hend... at microcorp.co.za>
> wrote:
>
>   
>> (i)  a True if All the elements in match are in aList, else False?
>> (ii) a True if any one or more of the members of match  are in aList?
>> (iii)  Something else?
>>     
>
>
> That's a good question because I failed miserably in explaining my
> problem clearly. My original question isn't what I'm trying to solve.
> My apologies. I will try to explain here clearly. I'm using a 3rd-
> party library named Selenium (used for web-automation) and it has a
> method named is_element_present(ele) i.e. takes one element and return
> true if it finds this element in the page's HTML and returns false
> otherwise. Given this, I'm just trying to write a method
> are_elements_present(aList) whose job is to return True if and only if
> all elements in aList are present in page's HTML. So here is how
> are_elements_present() looks like
>
>
>   def are_elements_present(eleLocators):
>     elePresent=False
>     if not eleLocators:
>         return False
>
>     for ele in eleLocators:
>         if selenium.is_element_present(ele):
>             elePresent=True
>         else:
>             elePresent=False
>             print 'cannot find this element= '+str(ele)
>             break
>     return elePresent
>
>
>
> Now suppose page HTML contains with these IDs ( ID is an attribute
> like <input id="inp1" />) = div1,div2,div3,div4,div5,inp1,inp2
> and if I call the above method this way are_elements_present
> ([div1,div2,inp1,inp2]) then it should return True. If I call like
> are_elements_present([div1,div2,div10,inp1]) it should return False.
> So I hope I've explained myself. Now all I'm looking for is to write
> are_elements_presents() in a more Pythonic way. So please let me know
> if I can write are_elements_present() in more smart/shorter way.
>
> Thanks a lot for your help, in advance.
> Best regards,
> Oltmans
>
>
>   
def are_all_elements_present(elems):
    if not elems:
        return False                  #because you want it "backward"
    return all(  selenium.is_element_present(elem) for elem in elems )

The extra check is there because you're specifying that an empty list 
should return False, and all() returns True if no matches.

DaveA




More information about the Python-list mailing list