Skip to content

Commit

Permalink
fight mypy[1]
Browse files Browse the repository at this point in the history
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]: python/mypy#1153
[2]: https://github.com/lilydjwg/nvchecker/actions/runs/4916840821/jobs/8793454970
  • Loading branch information
lilydjwg committed May 9, 2023
1 parent 62a3f33 commit af77af3
Show file tree
Hide file tree
Showing 3 changed files with 24 additions and 13 deletions.
12 changes: 8 additions & 4 deletions nvchecker/core.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
from typing import (
Tuple, NamedTuple, Optional, List, Union,
cast, Dict, Awaitable, Sequence, Any,
TYPE_CHECKING,
)
import types
from pathlib import Path
Expand All @@ -22,10 +23,13 @@

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

Expand Down
11 changes: 7 additions & 4 deletions nvchecker/util.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,10 +14,13 @@
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

Expand Down
14 changes: 9 additions & 5 deletions tests/conftest.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,11 +5,15 @@
import structlog
import os
from pathlib import Path

try:
import tomllib
except ModuleNotFoundError:
import tomli as tomllib # type: ignore
from typing import TYPE_CHECKING

if TYPE_CHECKING:
import tomli as tomllib
else:
try:
import tomllib
except ModuleNotFoundError:
import tomli as tomllib

import pytest
import pytest_asyncio
Expand Down

2 comments on commit af77af3

@hauntsaninja
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Use:

if sys.version_info >= (3, 11):
    import tomllib
else:
    import tomli as tomllib

@lilydjwg
Copy link
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes that will work too, but I don't want to do version check for a feature that can be added by a third party (i.e. a backported module).

Please sign in to comment.