MCPcopy
hub / github.com/pytest-dev/pytest / importorskip

Function importorskip

src/_pytest/outcomes.py:198–286  ·  view source on GitHub ↗

Import and return the requested module ``modname``, or skip the current test if the module cannot be imported. :param modname: The name of the module to import. :param minversion: If given, the imported module's ``__version__`` attribute must be at least this min

(
    modname: str,
    minversion: str | None = None,
    reason: str | None = None,
    *,
    exc_type: type[ImportError] | None = None,
)

Source from the content-addressed store, hash-verified

196
197
198def importorskip(
199 modname: str,
200 minversion: str | None = None,
201 reason: str | None = None,
202 *,
203 exc_type: type[ImportError] | None = None,
204) -> Any:
205 """Import and return the requested module ``modname``, or skip the
206 current test if the module cannot be imported.
207
208 :param modname:
209 The name of the module to import.
210 :param minversion:
211 If given, the imported module's ``__version__`` attribute must be at
212 least this minimal version, otherwise the test is still skipped.
213 :param reason:
214 If given, this reason is shown as the message when the module cannot
215 be imported.
216 :param exc_type:
217 The exception that should be captured in order to skip modules.
218 Must be :py:class:`ImportError` or a subclass.
219
220 Defaults to :class:`ModuleNotFoundError` when not given, which means
221 the module must be missing for the test to be skipped.
222 Pass ``exc_type=ImportError`` to also skip modules that raise
223 :class:`ImportError` during import.
224
225 See :ref:`import-or-skip-import-error` for details.
226
227
228 :returns:
229 The imported module. This should be assigned to its canonical name.
230
231 :raises pytest.skip.Exception:
232 If the module cannot be imported.
233
234 Example::
235
236 docutils = pytest.importorskip("docutils")
237
238 .. versionadded:: 8.2
239
240 The ``exc_type`` parameter.
241
242 .. versionchanged:: 9.1
243
244 The default for ``exc_type`` is now :class:`ModuleNotFoundError`.
245 """
246 import warnings
247
248 __tracebackhide__ = True
249 compile(modname, "", "eval") # to catch syntaxerrors
250
251 # Keep the public signature compatible while using the pytest 9.1 default behavior.
252 if exc_type is None:
253 exc_type = ModuleNotFoundError
254
255 skipped: Skipped | None = None

Callers 3

spawnMethod · 0.90
fFunction · 0.85
test_importorskipFunction · 0.85

Calls 1

SkippedClass · 0.85

Tested by 3

spawnMethod · 0.72
fFunction · 0.68
test_importorskipFunction · 0.68