Skip to content

Assume if TYPE_CHECKING: ... else: ... block is covered #831

Closed

Description

@retnikt

if typing.TYPE_CHECKING blocks are never run but are still counted as needing test coverage.
( https://docs.python.org/3.7/library/typing.html#typing.TYPE_CHECKING )

Example

from typing import TYPE_CHECKING
if TYPE_CHECKING:
    # coverage.py thinks this is not covered because TYPE_CHECKING is True at runtime
    ...
else:
    ....

You have to add # pragma: no_cover to the if block here because coverage.py assumes TYPE_CHECKING to be False, and therefore assumes one of the blocks does not have a test case. It would be good if you didn't have to, and blocks requiring TYPE_CHECKING to be True are assumed to not need test cases.

Activity

  1. added
    bug
    on Aug 2, 2019
  2. nedbat commented on Aug 2, 2019

    @nedbat
    Member

    You can solve this yourself today by adding this to your .coveragerc file:

    [report]
    exclude_lines = 
        pragma: no cover
        if TYPE_CHECKING:
    

    More details about this setting are here: Advanced exclusion.

    Since this is something that is configurable by the user, I would rather not change coverage.py to deal with it.

  3. cjw296 commented on Jan 24, 2022

    @cjw296

    @nedbat - when would you expect code inside if TYPE_CHECKING blocks to be executed while code coverage measurement is in effect? How would you feel about making this part of the default exclude_lines?

  4. nedbat commented on Jan 24, 2022

    @nedbat
    Member

    A few years later, I think you are right that it should be part of the default. If the user wants to measure those lines, they can.

  5. reopened this on Jan 24, 2022
  6. ikonst commented on Apr 6, 2022

    @ikonst

    Can we also add ... to the defaults while we're at it?

  7. cjw296 commented on Apr 7, 2022

    @cjw296

    @ikonst - I'm not 100% sure that's a good idea, but also as I've painfully discovered, you really mean \.\.\..

  8. ikonst commented on Apr 7, 2022

    @ikonst

    Yeah, obviously in its escaped form. I think the sharp change in coverage would tell you :)

  9. cjw296 commented on Apr 7, 2022

    @cjw296

    It can be quite the footgun when your projects are starting from 100% line coverage...

  10. 39 remaining items

  11. nedbat commented on Jul 17, 2025

    @nedbat
    Member

    I guess I'm also a bit concerned that someone could have their own user-defined base class called Protocol, and I'd inadvertently exclude entire classes.

  12. KSmanis commented on Jul 17, 2025

    @KSmanis

    Do people actually use Protocol in multiple inheritance?

    Random example in the wild: https://mypy.readthedocs.io/en/stable/protocols.html#defining-subprotocols-and-subclassing-protocols

    Can be addressed by r"class .+\(.*\bProtocol\b.*\):" (without taking into account multi-line cases).

    I guess I'm also a bit concerned that someone could have their own user-defined base class called Protocol, and I'd inadvertently exclude entire classes.

    Yeah, regexes can only get you so far; a proper solution would require AST parsing. Maybe just mention it in the docs so that users can apply it on their own?

  13. nedbat commented on Jul 22, 2025

    @nedbat
    Member

    I just learned that ruff will reformat code so that this:

    def foo():
        ...
    

    becomes:

    def foo(): ...
    

    which changes my perspective on the inline ellipsis.

    Perhaps the ellipsis regex should be:

    r"^\s*(def .*: )?\.\.\.\s*(#|$)",
    
  14. KSmanis commented on Jul 22, 2025

    @KSmanis

    Off the top of my head:

    Some false negatives:

    class AsyncProto(Protocol):
        async def __call__(self): ...
    
    
    class MultilineProto(Protocol):
        def __call__(
            self,
            some_args,
            more_args,
        ): ...
    
    
    class TypedProto(Protocol):
        def __call__(self) -> None: ...

    A false positive:

    class Model(PydanticModel):
         long_field = Field(
             ...,
             description="long field",
         )
  15. nedbat commented on Jul 22, 2025

    @nedbat
    Member

    The false negatives are great examples, thanks. The false positive wouldn't match because of the comma, right?

  16. KSmanis commented on Jul 22, 2025

    @KSmanis

    True, the false positive could be only triggered by an unformatted (and quite odd):

    class Model(PydanticModel):
         field = Field(
             ...
         )
  17. cjw296 commented on Jul 22, 2025

    @cjw296

    @KSmanis - let's not let perfect be the enemy of good - your example is weird enough I'd be happy for the fix for it to be "please format your code differently" :-)

    (if I ended up with a need for that layout, I'd be totally fine with a custom exclude or just comment exclude!)

  18. KSmanis commented on Jul 22, 2025

    @KSmanis

    Of course, I'm not advocating for it to be considered. IMO a regex for Protocols and overloads would cover most common cases, rather than trying to perfect a regex for Ellipsis.

  19. cjw296 commented on Jul 22, 2025

    @cjw296

    Separate refex in the defaults to cover those two is a great suggestion!

  20. nedbat commented on Jul 22, 2025

    @nedbat
    Member

    I'm still concerned that matching the words "overload" or "Protocol" will have false positives. People can configure those extra regexes themselves. Am I wrong to be concerned?

  21. nedbat commented on Jul 23, 2025

    @nedbat
    Member

    In commit 4d4ddd8 I made the ellipsis pattern (much) more elaborate:

    r"^\s*(((async )?def .*?)?\)(\s*->.*?)?:\s*)?\.\.\.\s*(#|$)",

    This works for all the real cases we've identified, but still has a false positive:

    def f(): print("(well): ... #2 false positive!")

    I think it strikes a good balance.

  22. nedbat commented on Jul 24, 2025

    @nedbat
    Member

    This is now released as part of coverage 7.10.0.

  23. nedbat commented on Jul 26, 2025

    @nedbat
    Member

    Oops, the if TYPE_CHECKING: exclusion was wrong, fixed in commit 1e2f41a

  24. nedbat commented on Jul 27, 2025

    @nedbat
    Member

    This is now released as part of coverage 7.10.1.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    enhancementfixed

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions