From af77af34f33224bd3b103f0bb4a3da22a208a51b Mon Sep 17 00:00:00 2001 From: lilydjwg Date: Tue, 9 May 2023 13:31:11 +0800 Subject: [PATCH] fight mypy[1] The following error will be reported without if: error: Name "tomllib" already defined (by an import) While this can be silenced by a "# type: ignore", in some case[2] mypy will report the following error: error: Unused "type: ignore" comment [1]: https://github.com/python/mypy/issues/1153 [2]: https://github.com/lilydjwg/nvchecker/actions/runs/4916840821/jobs/8793454970 --- nvchecker/core.py | 12 ++++++++---- nvchecker/util.py | 11 +++++++---- tests/conftest.py | 12 ++++++++---- 3 files changed, 23 insertions(+), 12 deletions(-) diff --git a/nvchecker/core.py b/nvchecker/core.py index def7afa..7875298 100644 --- a/nvchecker/core.py +++ b/nvchecker/core.py @@ -12,6 +12,7 @@ import argparse from typing import ( Tuple, NamedTuple, Optional, List, Union, cast, Dict, Awaitable, Sequence, Any, + TYPE_CHECKING, ) import types from pathlib import Path @@ -22,10 +23,13 @@ import json import structlog -try: - import tomllib -except ModuleNotFoundError: - import tomli as tomllib # type: ignore +if TYPE_CHECKING: + import tomli as tomllib +else: + try: + import tomllib + except ModuleNotFoundError: + import tomli as tomllib import platformdirs diff --git a/nvchecker/util.py b/nvchecker/util.py index c6456e3..8d006f4 100644 --- a/nvchecker/util.py +++ b/nvchecker/util.py @@ -14,10 +14,13 @@ from pathlib import Path import contextvars import abc -try: - import tomllib -except ModuleNotFoundError: - import tomli as tomllib # type: ignore +if TYPE_CHECKING: + import tomli as tomllib +else: + try: + import tomllib + except ModuleNotFoundError: + import tomli as tomllib import structlog diff --git a/tests/conftest.py b/tests/conftest.py index efa9d76..17b4b2e 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -5,11 +5,15 @@ import asyncio import structlog import os from pathlib import Path +from typing import TYPE_CHECKING -try: - import tomllib -except ModuleNotFoundError: - import tomli as tomllib # type: ignore +if TYPE_CHECKING: + import tomli as tomllib +else: + try: + import tomllib + except ModuleNotFoundError: + import tomli as tomllib import pytest import pytest_asyncio