Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pythonic alternatives to if/else statements

I'm trying to avoid a complex web of if/elif/else statements.

What pythonic approaches can I use to accomplish my goal.

Here's what I want to achieve:

My script will receive a slew of different urls,

youtube.com, hulu.com, netflix.com, instagram.com, imgur.com, etc, etc possibly 1000s of different domains.

I will have a function/set of different instructions that will be called for each distinct site.

so....

    if urlParsed.netloc == "www.youtube.com":
        youtube()
    if urlParsed.netloc == "hulu.com":
        hulu()
    and so on for 100s of lines....

Is there anyway to avoid this course of action...if xyz site do funcA, if xyz site do funcB.

I want to use this as a real world lesson to learn some advance structuring of my python code. So please feel free to guide me towards something fundamental to Python or programming in general.

like image 658
sirvon Avatar asked Oct 13 '13 08:10

sirvon


People also ask

What can I use instead of if-else statements?

Some alternatives to the if-else statement in C++ include loops, the switch statement, and structuring your program to not require branching.

What can I use instead of multiple if statements in Python?

Take Advantage of the Boolean Values. There's no need to have the if/else statements. Instead, we can use the boolean values. In Python, True is equal to one , and False is equal to zero .

Why does Python use Elif instead of else if?

The elif is short for else if. It allows us to check for multiple expressions. If the condition for if is False , it checks the condition of the next elif block and so on. If all the conditions are False , the body of else is executed.


1 Answers

Use a dispatch dictionary mapping domain to function:

def default_handler(parsed_url):
    pass

def youtube_handler(parsed_url):
    pass

def hulu_handler(parsed_url):
    pass

handlers = {
    'www.youtube.com': youtube_handler,
    'hulu.com':        hulu_handler,
}

handler = handlers.get(urlParsed.netloc, default_handler)
handler(urlParsed)

Python functions are first-class objects and can be stored as values in a dictionary just like any other object.

like image 50
Martijn Pieters Avatar answered Sep 23 '22 15:09

Martijn Pieters