While writing python code (I write python-selenium for GUI automation), I am facing situations wheer I have to deal with 5 widgets that do the same thing, just there xpath is differs by one term.
# set value of a type of web element to x
try:
if not some_web_element.checkExists():
report('X does not exist')
some_web_element.set(x)
if not some_web_element.a():
# blah blah
if not some_web_element.b():
# blah blah
except:
# blah blah
# set value another web element of same type to y
try:
if not another_web_element_of_same_type.checkExists():
report('Y does not exist')
another_web_element_of_same_type.set(y)
if not another_web_element_of_same_type.a():
# blah blah
if not another_web_element_of_same_type.b():
# blah blah
except:
# blah blah
# do this for 4 or 5 more elements
Alternate:
def action_func(web_elm, elm_name, param1=val1 .....):
try:
if not web_elm.checkExists():
report('{} does not exist'.format(elm_name))
web_elm.set(x)
if not web_elm.a():
# blah blah
if not web_elm.b():
# blah blah
# do more carbon copy operations based on pram list
except:
# blah blah
action_func(some_web_element, 'X', ........)
action_func(some_web_element, 'Y', ........)
action_func(some_web_element, 'Z', ........)
action_func(some_web_element, 'X', ........)
What is better purely for efficiency for Python theoretically:
- line by line execution causes redundant code to be executed fast as no module required to be loaded, OR
- smaller functions faster to load and hence more efficient than loading more LOC