I sometimes forget to return result from a function:
def f(*args):
# do stuff
result = # an expression
# oops forgot to return result
Since None is a valid value in my application, this does not raise any exception or even any alarm in the caller. Of course, I’m trying to be careful. But I was wondering if there’s some neat approach to warn me about any function that doesn’t explicitly return a value.
Perhaps a regex I can run through my code to find such cases. Or some code checking tool (hopefully available under the Windows environment).
I was even thinking using a decorator like this:
def requires_return(func):
def new_func(*args, **kwargs):
result = func(*args, **kwargs)
if result is None:
print('Warning: {} may be missing a return statement'.format(func.__name__))
return result
But this wouldn’t work because:
-
Many false alarms: each time a function actually returns
None. I can’t stop usingNonein my application without creating really ugly code elsewhere. -
In any case, adding a decorator to every function seems super-ugly.
Note that I do have functions where I intentionally don’t have a return statement. I tend to maintain a certain naming convention, which allows me easily to distinguish them. (Specifically, every function that starts with get_ must have a return statement.)
Pylint will sometimes catch this kind of error. In particular if you assign to
resultbut then never use it:However, it does not catch the case where you build up
resultin pieces and then forget to return it (because then the variable is not “unused”).Depending on many other things, though, pylint, through its static type-analysis, may catch the failure to return a value.