Forem

Cover image for TIL: exclude_also with coverage.py
Hugo van Kemenade
Hugo van Kemenade

Posted on • Edited on

4

TIL: exclude_also with coverage.py

Sometimes you have code you want to exclude from the test coverage report, because it doesn't really make sense to test it.

For example, maybe you want to exclude:

if __name__ == "__main__":
    main()
Enter fullscreen mode Exit fullscreen mode

The old advice was to add something like this to .coveragerc:

[report]
# Regexes for lines to exclude from consideration
exclude_lines =
    # Have to re-enable the standard pragma:
    pragma: no cover

    # Don't complain if non-runnable code isn't run:
    if __name__ == .__main__.:
Enter fullscreen mode Exit fullscreen mode

But since coverage.py 7.2.0 (2023-02-22) you can use exclude_also instead and skip that pragma:

[report]
# Regexes for lines to exclude from consideration
exclude_also =
    # Don't complain if non-runnable code isn't run:
    if __name__ == .__main__.:
Enter fullscreen mode Exit fullscreen mode

Which is:

 [report]
 # Regexes for lines to exclude from consideration
-exclude_lines =
-    # Have to re-enable the standard pragma:
-    pragma: no cover
-
+exclude_also =
     # Don't complain if non-runnable code isn't run:
     if __name__ == .__main__.:
Enter fullscreen mode Exit fullscreen mode

Thanks

To Brian Okken for the tip.

To Ned Batchelder for maintaining Coverage.py.

To the Library of Congress and Flickr Commons for the photo of a covered wagon.

Do your career a big favor. Join DEV. (The website you're on right now)

It takes one minute, it's free, and is worth it for your career.

Get started

Community matters

Top comments (0)

👋 Kindness is contagious

Discover a treasure trove of wisdom within this insightful piece, highly respected in the nurturing DEV Community enviroment. Developers, whether novice or expert, are encouraged to participate and add to our shared knowledge basin.

A simple "thank you" can illuminate someone's day. Express your appreciation in the comments section!

On DEV, sharing ideas smoothens our journey and strengthens our community ties. Learn something useful? Offering a quick thanks to the author is deeply appreciated.

Okay