[TIP] Test runner checking for absence of 'None' in all functions (pytest)

Ned Batchelder ned at nedbatchelder.com
Sat Jan 23 16:59:20 PST 2016


On 1/23/16 4:27 PM, David wrote:
> Dear fellow Pythonistas,
>
> I am currently reading a book [1] that gives the following coding tip:
> "Prefer	Exceptions to Returning	None". You can see code examples out of
> the book further below.
>
> As I am teaching myself pytest these days, I would like to write a test
> runner (which eventually is to be part of a Continuous Integration
> setup) that fails should it detect any function that returns None.
This sounds like a job for pyflakes or pylint, not a test runner. 
Especially because a function with no return statement at all will 
return None. It sounds like you want to find explicit "return None" 
statements.  Static analysis such as pylint does sounds right for this job.

--Ned.
> My problem is that I would like to limit the test runner to look
> *inside* of functions (and/or other structures).
>
> I can very well write a parser that checks, per line, if the words
> "return" and "None" are used. But that would cover the entire file in
> question, never mind its structure.
>
> Do you have any ideas how to check the 'absence of None' within
> functions and the like?
>
> I am looking forward to your suggestions!
>
> Greetings and thanks,
>
> David
>
>
>
>
> # bad code
> def divide(a, b):
>      try:
>          return a / b
>      except ZeroDivisionError:
> 	return None
>
>
> # good code
> def divide(a, b):
>      try:
> 	return a / b
>      except ZeroDivisionError as e:
> 	raise ValueError(‘Invalid inputs’) from	e
>
>
> [1] Brett Slatkin (2015), Effective Python, Addison-Wesley
>
> _______________________________________________
> testing-in-python mailing list
> testing-in-python at lists.idyll.org
> http://lists.idyll.org/listinfo/testing-in-python




More information about the testing-in-python mailing list