Skip to content

Make pytest.importorskip() a context manager to preserve typing #15448

Backlog

Description

@The-Compiler

When using pytest.importorskip(), type information is lost:

import pytest
from typing import reveal_type

requests = pytest.importorskip("requests")
reveal_type(requests)

def test_requests() -> None:
    requests.getttt(...)
$ mypy --strict test_requests.py
test_requests.py:5: note: Revealed type is "Any"
Success: no issues found in 1 source file

vs.

import pytest

try:
    import requests
except ModuleNotFoundError:
    pytest.skip("requests not found")
$ mypy --strict test_requests.py
test_requests.py:10: note: Revealed type is "types.ModuleType"
test_requests.py:13: error: Module has no attribute "getttt"  [attr-defined]
Found 1 error in 1 file (checked 1 source file)

Other than perhaps a mypy specific plugin, I don't see a way around this with the current API. However, it would all work nicely (and also IMHO makes things nicer because it avoids the duplicated module type, supports from imports, makes things work for other static analyzers, etc.) if pytest.importorskip() was a context manager instead:

with pytest.importorskip():
    import requests
    from requests import RequestException

Activity

  1. PalakshiVerma commented on Nov 24, 2026

    @PalakshiVerma
  2. RonnyPfannschmidt commented on Nov 24, 2026

    @RonnyPfannschmidt
    Member

    @PalakshiVerma that message reads like a llm hallucination mixed with excess information vomit so please step back and rethink how you interact with the world

    @The-Compiler i'd prefer a new name for this as a mixed api seems rather confusing to me

    however we are in a kind of blind wrt names as importorskip is the most sensible name for this painfull mess

  3. The-Compiler commented on Nov 24, 2026

    @The-Compiler
    MemberAuthor

    I think a new (similar) name would be even more confusing. I also think the mixed API kind of thing has a precedent with pytest.raises(<exc>, <func>, *<args>) vs. with pytest.raises(<exc>):. Over time, we could also (soft-)deprecate the old form.

  4. Meeth-webdev commented on Nov 26, 2026

    @Meeth-webdev

    Hi @RonnyPfannschmidt @The-Compiler , I would like to take up the issue and below is the plan which I might follow :

    Implementation:

    • In my implementation I have planned to make a helper function def _importorskip_cm which takes reason and exc_type as parameter and the decorator contextlib.contextmanager , which makes the helper function a context manager . I made sure to have a look as to how this decorator was used previously .
    image (NOTE : The image does not contain the parameter : min_version , because its a design decision which I will discuss below).
    • I have used function overloading to make sure the context manager scenario and the current scenario are both accepted .
    image
    • In the context_manager scenario modname is not passed (as the module is imported in the body of the with statement) . Keeping that in mind , if the modname comes as None then I pass the two parameters to the helper function and return what that helper function returns .
    image

    Min version parameter :

    The context manager will need to learn about which module to check . We can maybe do it through the below way :

    with pytest.importorskip() as skipper:
        import requests
        skipper.require_version(requests, "2.0")
    

    This will allow the user to check version for different modules within the same 'with' block.

    To implement this we will need to define a helper class which will have the function def require_version . The _importorskip_cm will yield this helper .

    @contextmanager
    def _importorskip_cm(...) -> Iterator[_ImportOrSkip]:
        helper = _ImportOrSkip()
        try:
            yield helper          # was: yield
        except exc_type as exc:
            raise Skipped(...) from None
    
    The helper class
    
    class _ImportOrSkip:
        def require_version(self, module: ModuleType, minversion: str) -> None:
            __tracebackhide__ = True
            from packaging.version import Version
    
            verattr = getattr(module, "__version__", None)
            if verattr is None or Version(verattr) < Version(minversion):
                raise Skipped(
                    f"module {module.__name__!r} has __version__ {verattr!r}, "
                    f"required is: {minversion!r}",
                    allow_module_level=True,
                )
    

    (It reuses the same logic applied in the current scenario).

    Addressing the Any Error :

    The Any type error gets eliminated with the use of context manager , because as @The-Compiler stated , the import happens which allows mypy to do the static type checking .

    Please let me know if any refinements are needed , if not I would like to open a PR for this issue .

    Thanks !!!

  5. RonnyPfannschmidt commented on Nov 26, 2026

    @RonnyPfannschmidt
    Member

    🤖 Written by Claude Opus 5.5 via Claude Code for the pytest maintainers; I prompted it, it did the work, I read it.

    The skipper.require_version() helper is more API than this needs right now. A good starting point is the plain form only:

    with pytest.importorskip():
        import requests

    That means the context manager catches the import error and skips with the same semantics as today, including reason and the ModuleNotFoundError/ImportError warning behaviour. It has typing overloads and tests. It doesn't do min-version handling: a version check can be a follow-up once the basic form has landed, and the naming question above is still open.

    Please post code as text, not screenshots. A draft PR is the best place for it.


    Generated by Claude Code

  6. Meeth-webdev commented on Nov 26, 2026

    @Meeth-webdev

    Hi @RonnyPfannschmidt thanks for the review , I will make sure to keep the context manager version which does not have min_version for now .

    Thank you , I will be opening a draft PR shortly .

  7. added a commit that references this issue on Nov 26, 2026
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

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions