You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
Make pytest.importorskip() a context manager to preserve typing #15448
$ mypy --strict test_requests.pytest_requests.py:5: note: Revealed type is "Any"Success: no issues found in 1 source file
vs.
importpytesttry:
importrequestsexceptModuleNotFoundError:
pytest.skip("requests not found")
$ mypy --strict test_requests.pytest_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:
@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
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.
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 .
(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 .
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 .
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 .
🤖 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:
withpytest.importorskip():
importrequests
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.
Activity
PalakshiVerma commentedon Nov 24, 2026
RonnyPfannschmidt commentedon Nov 24, 2026
@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
The-Compiler commentedon Nov 24, 2026
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.Meeth-webdev commentedon Nov 26, 2026
Hi @RonnyPfannschmidt @The-Compiler , I would like to take up the issue and below is the plan which I might follow :
Implementation:
Min version parameter :
The context manager will need to learn about which module to check . We can maybe do it through the below way :
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 .
(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 !!!
RonnyPfannschmidt commentedon Nov 26, 2026
🤖 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:That means the context manager catches the import error and skips with the same semantics as today, including
reasonand 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
Meeth-webdev commentedon Nov 26, 2026
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 .
Add Meeth Gangwar to AUTHORS