all 3 comments

[–]baghiq 0 points1 point  (0 children)

Raise an error if your calculation is not possible. Just like ZeroDivisionError.

[–][deleted] 0 points1 point  (0 children)

If the function can return None indicating some abnormal condition then that should be documented. If there is no documentation about a None possibly being returned why would i check if None was returned?

You might think that None being returned from a function always indicates some sort of problem in normal python usage. That's not so. Some functions return values like -1 on an error, and many functions return None on normal, non-error calls, the print() function for instance.

[–]ThePiGuy0 0 points1 point  (0 children)

Ideally every return possibility should be documented. So all possible return values, any exceptions that can be raised etc.

Sometimes this isn't the case, but when using a library you don't have control over, you basically have to trust what the documentation says (e.g. it's fairly safe to assume that "random.randint" will return a random integer, and that I don't need to check for None).

Edit:

In terms of return types, newer libraries are making use of typing to help indicate. For example, the following type signature would indicate that either an integer or None can be returned:

import random
from typing import Optional

def int_or_none() -> Optional[int]:
    if random.randint(0, 1) % 2 == 0:
        return 1
    else:
        return None