Hamza Cavus
Hamza Cavus

Reputation: 79

Python How to avoid many if statements

I'll try to simplify my problem. I'm writing a test program using py.test and appium. Now:

In the application I have 4 media formats: Video, Audio, Image and Document. I have a control interface with previous, next, play , stop buttons. Each media formats has a unique ID like

video_playbutton, audio_playbutton, document_playbutton, image_playbutton, video_stopbutton audio_stopbutton ...etc etc.

But the operation I have to do is the same for all of them e.g press on playbutton.

I can address playbutton of each when i give them explicitly like this

find_element_by_id("video_playbutton")

And when i want to press on other playbuttons I've to repeat above line each time. Like this:

find_element_by_id("video_playbutton")
find_element_by_id("audio_playbutton")
find_element_by_id("image_playbutton")
find_element_by_id("document_playbutton")

And because I'm calling this function from another script I would have to distinguish first what string I got e.g:

def play(mediatype):
    if mediatype == "video"
          el = find_element_by_id("video_playbutton")
          el.click()
    if mediatype == "audio"
          el = find_element_by_id("audio_playbutton")
          el.click()
    if .....

What is the best way to solve this situation? I want to avoid hundreds of if-statements because there is also stop, next , previous etc buttons.

I'm rather searching for something like this

def play(mediatype)
    find_element_by_id(mediatype.playbutton)

Upvotes: 2

Views: 705

Answers (1)

Vinayak Kolagi
Vinayak Kolagi

Reputation: 1881

You can separate out the selectors and operations in two dictionaries which scales better. Otherwise the mapping eventually gets huge. Here is the example.

dictMedia = {'video':['video_playbutton', 'video_stopbutton','video_nextbutton'], 'audio':['audio_playbutton', 'audio_stopbutton', 'audio_nextbutton']}
dictOperations = {'play':0, 'stop':1, 'next':2}
def get_selector(mediatype, operation):
    return dictMedia[mediatype][dictOperations[operation]]

print get_selector('video', 'play')

PS: The above operation doesn't check for key not found errors. However, I still feel, if the media specific operations grow, then a page object model would be better.

Upvotes: 2

Related Questions