[TIP] Test runner checking for absence of 'None' in all functions (pytest)
holger krekel
holger at merlinux.eu
Sun Jan 24 02:30:44 PST 2016
On Sat, Jan 23, 2016 at 22:27 +0100, 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.
There are in my experience also good examples of returning None.
Sometimes it's nicer on the caller side to not have to handle
exceptions. Also some_dict_object.get(key) returns None if the key is
not in the dictionary. Then again, not hiding exceptions is a good idea
as well in many cases like in the divide function 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.
FWIW "return None" can only appear in a function. At module level it
will raise a SyntaxError. Also functions can implicitely return
None if they don't have a return statement in all code paths.
> Do you have any ideas how to check the 'absence of None' within
> functions and the like?
Not completely sure but maybe checking at the bytecode level
might work better.
holger
> 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
--
about me: http://holgerkrekel.net/about-me/
contracting: http://merlinux.eu
More information about the testing-in-python
mailing list