Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

tag: only import typing_extensions when TYPE_CHECKING #254

Merged
merged 4 commits into from
Aug 6, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion doc/upload-docs.sh
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
#! /bin/sh

rsync --verbose --archive --delete _build/html/* doc-upload:doc/pytools
rsync --verbose --archive --delete _build/html/ doc-upload:doc/pytools
3 changes: 3 additions & 0 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -110,8 +110,11 @@ known-local-folder = [
lines-after-imports = 2

[tool.mypy]
python_version = "3.8"
ignore_missing_imports = true
warn_unused_ignores = true
# TODO: enable this at some point
# check_untyped_defs = true

[tool.typos.default]
extend-ignore-re = [
Expand Down
23 changes: 15 additions & 8 deletions pytools/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@
from functools import reduce, wraps
from sys import intern
from typing import (
TYPE_CHECKING,
Any,
Callable,
ClassVar,
Expand All @@ -52,15 +53,21 @@
)


try:
from typing import Concatenate, SupportsIndex
except ImportError:
from typing_extensions import Concatenate, SupportsIndex
if TYPE_CHECKING:
# NOTE: mypy seems to be confused by the `try.. except` below when called with
# python -m mypy --python-version 3.8 ...
# see https://github.com/python/mypy/issues/14220
from typing_extensions import Concatenate, ParamSpec, SupportsIndex
else:
try:
from typing import Concatenate, SupportsIndex
except ImportError:
from typing_extensions import Concatenate, SupportsIndex

try:
from typing import ParamSpec
except ImportError:
from typing_extensions import ParamSpec # type: ignore[assignment]
try:
from typing import ParamSpec
except ImportError:
from typing_extensions import ParamSpec # type: ignore[assignment]


# These are deprecated and will go away in 2022.
Expand Down
2 changes: 1 addition & 1 deletion pytools/convergence.py
Original file line number Diff line number Diff line change
Expand Up @@ -75,7 +75,7 @@ def estimate_order_of_convergence(self,
gliding_mean = size

data_points = size - gliding_mean + 1
result = np.zeros((data_points, 2), float)
result: np.ndarray = np.zeros((data_points, 2), float)
for i in range(data_points):
result[i, 0], result[i, 1] = estimate_order_of_convergence(
abscissae[i:i+gliding_mean], errors[i:i+gliding_mean])
Expand Down
13 changes: 10 additions & 3 deletions pytools/graph.py
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,7 @@

from dataclasses import dataclass
from typing import (
TYPE_CHECKING,
Any,
Callable,
Collection,
Expand All @@ -83,10 +84,16 @@
)


try:
from typing import TypeAlias
except ImportError:
if TYPE_CHECKING:
# NOTE: mypy seems to be confused by the `try.. except` below when called with
# python -m mypy --python-version 3.8 ...
# see https://github.com/python/mypy/issues/14220
from typing_extensions import TypeAlias
else:
try:
from typing import TypeAlias
except ImportError:
from typing_extensions import TypeAlias


NodeT = TypeVar("NodeT", bound=Hashable)
Expand Down
8 changes: 6 additions & 2 deletions pytools/persistent_dict.py
Original file line number Diff line number Diff line change
Expand Up @@ -77,6 +77,10 @@

logger = logging.getLogger(__name__)

# NOTE: not always available so they get hardcoded here
SQLITE_BUSY = getattr(sqlite3, "SQLITE_BUSY", 5)
SQLITE_CONSTRAINT_PRIMARYKEY = getattr(sqlite3, "SQLITE_CONSTRAINT_PRIMARYKEY", 1555)

__doc__ = """
Persistent Hashing and Persistent Dictionaries
==============================================
Expand Down Expand Up @@ -574,7 +578,7 @@ def _exec_sql_fn(self, fn: Callable[[], T]) -> Optional[T]:
except sqlite3.OperationalError as e:
# If the database is busy, retry
if (hasattr(e, "sqlite_errorcode")
and not e.sqlite_errorcode == sqlite3.SQLITE_BUSY):
and e.sqlite_errorcode != SQLITE_BUSY):
raise
if n % 20 == 0:
warn(f"PersistentDict: database '{self.filename}' busy, {n} "
Expand Down Expand Up @@ -721,7 +725,7 @@ def store(self, key: K, value: V, _skip_if_present: bool = False) -> None:
self._exec_sql("INSERT INTO dict VALUES (?, ?)", (keyhash, v))
except sqlite3.IntegrityError as e:
if hasattr(e, "sqlite_errorcode"):
if e.sqlite_errorcode == sqlite3.SQLITE_CONSTRAINT_PRIMARYKEY:
if e.sqlite_errorcode == SQLITE_CONSTRAINT_PRIMARYKEY:
raise ReadOnlyEntryError("WriteOncePersistentDict, "
"tried overwriting key") from e
else:
Expand Down
12 changes: 9 additions & 3 deletions pytools/tag.py
Original file line number Diff line number Diff line change
Expand Up @@ -40,10 +40,16 @@
from warnings import warn


try:
from typing import Self, dataclass_transform
except ImportError:
if TYPE_CHECKING:
# NOTE: mypy seems to be confused by the `try.. except` below when called with
# python -m mypy --python-version 3.8 ...
# see https://github.com/python/mypy/issues/14220
from typing_extensions import Self, dataclass_transform
else:
try:
from typing import Self, dataclass_transform
except ImportError:
from typing_extensions import Self, dataclass_transform

from pytools import memoize, memoize_method

Expand Down
6 changes: 3 additions & 3 deletions pytools/test/test_pytools.py
Original file line number Diff line number Diff line change
Expand Up @@ -497,7 +497,7 @@ def vectorized_add(self, ary):
# }}}


def test_tag():
def test_tag() -> None:
from pytools.tag import (
NonUniqueTagError,
Tag,
Expand Down Expand Up @@ -552,7 +552,7 @@ class BestInClassRibbon(FairRibbon, UniqueTag):
# a subclass of Tag
with pytest.raises(TypeError):
check_tag_uniqueness(frozenset((
"I am not a tag", best_in_show_ribbon,
"I am not a tag", best_in_show_ribbon, # type: ignore[arg-type]
blue_ribbon, red_ribbon)))

# Test that instantiation succeeds if there are multiple instances
Expand Down Expand Up @@ -583,7 +583,7 @@ class BestInClassRibbon(FairRibbon, UniqueTag):

# Test that tagged() fails if tags are not a FrozenSet of Tags
with pytest.raises(TypeError):
t1.tagged(tags=frozenset((1,)))
t1.tagged(tags=frozenset((1,))) # type: ignore[arg-type]

# Test without_tags() function
t4 = t2.without_tags(red_ribbon)
Expand Down
Loading