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.
Some alternatives to the if-else statement in C++ include loops, the switch statement, and structuring your program to not require branching.
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 .
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With