DEV Community

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

Posted on • Updated on

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.

Top comments (0)