Guard clause
A guard clause helps you removing one level of nesting and resulting in flatter code.
Example
Before:
PYTHON
def is_gmail(email):if isinstance(email, str):if email.endswith("@gmail.com"):return Trueelse:return Falseelse:return False
After:
PYTHON
def is_gmail(email):if not isinstance(email, str):return Falseif not email.endswith("@gmail.com"):return Falsereturn True
Overkill?
Sometimes it is a bit of an overkill to use guard clause.
PYTHON
def drink(age):if age < 18:returnprint("Drinking...")
May be harder to read than just:
PYTHON
def drink(age):if age >= 18:print("Drinking...")