Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is this a good practice to write -> None everytime a function return nothing?

Tags:

python

Is this a good practice to write -> None when a function does not return anything ?

def nothing() -> None:
   print("Hey I'm not returning anything!")
like image 770
mR-Jacaj Avatar asked Mar 03 '23 18:03

mR-Jacaj


1 Answers

Yes, I would make a habit of this. If you're using type hints anyways, -> None is more consistent than leaving it blank.

If you change what the function returns as well, the type hint on the return will also help narrow down the cause of type warnings.


Previously, I had written:

With a good IDE, you will also get warnings if you try to use the return value of nothing:

# Warning: "Function 'nothing' doesn't return anything" (Pycharm)
a = nothing()

Surprise surprise though, Pycharm is actually smart enough to infer that anyway even without the annotation.

With a dumber IDE, it may still make a difference in warnings produced, although I would expect that any IDE that's smart enough to make use of -> None would also be smart enough to statically infer -> None.

like image 71
Carcigenicate Avatar answered Mar 05 '23 14:03

Carcigenicate