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

David ldl08 at gmx.net
Sat Jan 23 13:27:41 PST 2016


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.

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



More information about the testing-in-python mailing list