Most underrated Feature in python — P1 — Or is here

SanjayKhanSSK
2 min readJun 22, 2021

--

The hidden Power of or Keyword. this -> return datas if len(datas) > 0 else None -> to this -> return datas or None

#convert this toreturn datas if len(datas) > 0 else None#this (Super simple)return datas or None----------------------------------------------#convert this to return {(user["user_id"] if user["user_id"] != None else user["email_id"]) : "<user_detail>" for user in data}#this (0% complexity)return {(user["user_id"] or user["email_id"]) : "<user_detail>" for user in data}
Photo by Alexander Schimmeck on Unsplash

Hello World, Welcome back python is really really super user friendly, that we need to agree that.

But there are some features that we don’t know because of nobody is going to teach you when to use and it’s more reader friendly.

Today we’re going to see about or keyword, Again it’s a keyword so it’s built in. I don’t know about python2.x supports because i haven’t used python2.x

some_var = var_a or var_b

which means:

some_var= valid value or var_b

this or will return var_a if it’s true or len > 0 or not None else return var_b

let’s see some real world example 1:

query_pramas = request["qsp"] or {}

now the above example is getting the query_string_params from the URL(request), so if the no query_string_params is passed then the {} empty dict will get assigned

example 2:

def do_something():
#fetched datas from database
#need to pass the data to another function (if len(datas) > 0 else pass the None)
return datas or None

if you see above we haven’t calculated any length. if we want to use one line if to solve one, then

return datas if len(datas) > 0 else None

If you compare the above codes, you can understand the difference and more user friendly than the one line if else.

I’ll close this post with one final example that i used:

return {user["user_id"] or user["email_id"] : "<user_detail>" for user in data}

Now this will return dict of data with user id as key, if user_id is None, this will use email_id as key, this will prevent the None-TypeError Exception.

Ok, let’s use the power of or on all the places, Comment down if used or super different way and how. Bye 👋

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

--

--

No responses yet

Write a response