python - If thing exists, do something with thing -
what correct (pythonic) way this?
var = 'the quick brown fox' def exists(query, string): if query in string: return query else: return none if thing = exists('fox', var): print(thing.upper())
this example, i'm trying check if selenium web element exists. want avoid setting result variable because defeats purpose of "exists". also, don't want perform search twice returning true/false first time , again, if it's true, it.
this 1 of cases there's more 1 way it. few things do:
treat result collection of 0 1 elements (it makes more sense if call
find_one
in such cases):def find_one(query, string): if query in string: return [query] return []
then can use function in
for
loop:for existing_element in find_one(query, string): # existing element break else: # here if don't have elements (note `break` above)
pass callback first argument:
def if_exists(cb, query, string): if query in string: cb(query) def run_on_valid_query(q): # q if_exists(run_on_valid_query, query, string)
bite bullet , use intermediate variable:
result = extract_from(query, string) if result: # work here
Comments
Post a Comment