When a function never returns anything (i.e. returns None
), it doesn't require
an explicit return
at the end and early returns should be done without
providing any value:
# Correct
def greet(name: str) -> None:
print(f"Hello {name}!")
# Wrong
def greet(name: str) -> None:
print(f"Hello {name}!")
return
def greet(name: str) -> None:
print(f"Hello {name}!")
return None
# Correct
def log(message: str, *, silent: bool = False) -> None:
with LOG_FILE.open("a") as f:
f.write(message + "\n")
if silent:
return
print(message)
# Wrong
def log(message: str, *, silent: bool = False) -> None:
with LOG_FILE.open("a") as f:
f.write(message + "\n")
if silent:
return None
print(message)
When a function can return any other value, all cases in which None
would be
returned have to be explicitly stated including the value:
# Correct
def median(data: list[float]) -> float | None:
if not data:
return None
mid = len(data) // 2
if len(data) % 2 == 0:
return (data[mid - 1] + data[mid]) / 2
return data[mid]
# Wrong
def median(data: list[float]) -> float | None:
if not data:
return
mid = len(data) // 2
if len(data) % 2 == 0:
return (data[mid] + data[mid + 1]) / 2
return data[mid]
# Correct
def try_authenticating(username: str, password: str) -> str | None:
if username not in passwords:
return "Unknown user"
if passwords[username] != password:
return "Incorrect password"
return None
# Wrong
def try_authenticating(username: str, password: str) -> str | None:
if username not in passwords:
return "Unknown user"
if passwords[username] != password:
return "Incorrect password"
return
def try_authenticating(username: str, password: str) -> str | None:
if username not in passwords:
return "Unknown user"
if passwords[username] != password:
return "Incorrect password"