diff --git a/typeguard/pytest_plugin.py b/typeguard/pytest_plugin.py index b9b5b5f4..caa128b5 100644 --- a/typeguard/pytest_plugin.py +++ b/typeguard/pytest_plugin.py @@ -1,3 +1,5 @@ +import sys + from typeguard.importhook import install_import_hook @@ -8,8 +10,21 @@ def pytest_addoption(parser): 'type checking') -def pytest_sessionstart(session): - packages = session.config.getoption('typeguard_packages') - if packages: - package_list = [pkg.strip() for pkg in packages.split(',')] - install_import_hook(packages=package_list) +def pytest_configure(config): + value = config.getoption("typeguard_packages") + if not value: + return + + packages = [pkg.strip() for pkg in value.split(",")] + + already_imported_packages = sorted( + package for package in packages if package in sys.modules + ) + if already_imported_packages: + message = ( + "typeguard cannot check these packages because they " + "are already imported: {}" + ) + raise RuntimeError(message.format(", ".join(already_imported_packages))) + + install_import_hook(packages=packages)