diff options
author | Ned Batchelder <ned@nedbatchelder.com> | 2023-01-03 15:21:15 -0500 |
---|---|---|
committer | Ned Batchelder <ned@nedbatchelder.com> | 2023-01-03 15:29:00 -0500 |
commit | 4f3ccf213d813bb57775b2643b8bae5e08cbbbd0 (patch) | |
tree | fb113cb24362ee3fd67825867874ce3aa713b55e /coverage | |
parent | 98301ed240a141592573c2ed239e006d42a26161 (diff) | |
download | python-coveragepy-git-4f3ccf213d813bb57775b2643b8bae5e08cbbbd0.tar.gz |
refactor: a better way to have maybe-importable third-party modules
Diffstat (limited to 'coverage')
-rw-r--r-- | coverage/misc.py | 8 | ||||
-rw-r--r-- | coverage/tomlconfig.py | 6 |
2 files changed, 8 insertions, 6 deletions
diff --git a/coverage/misc.py b/coverage/misc.py index 1e4b4e74..bd1767ca 100644 --- a/coverage/misc.py +++ b/coverage/misc.py @@ -83,14 +83,16 @@ def import_third_party(modname): modname (str): the name of the module to import. Returns: - The imported module, or None if the module couldn't be imported. + The imported module, and a boolean indicating if the module could be imported. + + If the boolean is False, the module returned is not the one you want: don't use it. """ with sys_modules_saved(): try: - return importlib.import_module(modname) + return importlib.import_module(modname), True except ImportError: - return None + return sys, False def nice_pair(pair): diff --git a/coverage/tomlconfig.py b/coverage/tomlconfig.py index 31cd0bb0..737c728c 100644 --- a/coverage/tomlconfig.py +++ b/coverage/tomlconfig.py @@ -5,7 +5,6 @@ import os import re -import sys from typing import Any, Callable, Dict, Iterable, List, Optional, Tuple, Type, TypeVar @@ -17,9 +16,10 @@ from coverage.types import TConfigSection, TConfigValue if env.PYVERSION >= (3, 11, 0, "alpha", 7): import tomllib # pylint: disable=import-error + has_tomllib = True else: # TOML support on Python 3.10 and below is an install-time extra option. - tomllib = import_third_party("tomli") + tomllib, has_tomllib = import_third_party("tomli") class TomlDecodeError(Exception): @@ -51,7 +51,7 @@ class TomlConfigParser: toml_text = fp.read() except OSError: return [] - if sys.version_info >= (3, 11) or tomllib is not None: + if has_tomllib: try: self.data = tomllib.loads(toml_text) except tomllib.TOMLDecodeError as err: |