sirvon
sirvon

Reputation: 2625

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.

Upvotes: 7

Views: 3383

Answers (2)

Martijn Pieters
Martijn Pieters

Reputation: 1123400

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.

Upvotes: 15

thefourtheye
thefourtheye

Reputation: 239573

You can use a dict

myDict = {"www.youtube.com": youtube, "hulu.com": hulu}

...
...

if urlParsed.netloc in myDict:
    myDict[urlParsed.netloc]()
else:
    print "Unknown URL"

Upvotes: 4

Related Questions