Skip to content

Instantly share code, notes, and snippets.

@trag1c
Created June 13, 2023 22:53
Show Gist options
  • Save trag1c/1aa5b6b1cc92916b5521473e59ae3662 to your computer and use it in GitHub Desktop.
Save trag1c/1aa5b6b1cc92916b5521473e59ae3662 to your computer and use it in GitHub Desktop.
Working with None as the return type in Python

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"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment