Skip to content

Commit c5777ee

Browse files
committed
upgrade typeguard
1 parent 7617add commit c5777ee

31 files changed

+8439
-720
lines changed

metaflow/_vendor/typeguard/_checkers.py

Lines changed: 259 additions & 95 deletions
Large diffs are not rendered by default.

metaflow/_vendor/typeguard/_config.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
from __future__ import annotations
22

3-
from collections.abc import Collection
3+
from collections.abc import Iterable
44
from dataclasses import dataclass
55
from enum import Enum, auto
66
from typing import TYPE_CHECKING, TypeVar
@@ -49,11 +49,11 @@ class CollectionCheckStrategy(Enum):
4949
FIRST_ITEM = auto()
5050
ALL_ITEMS = auto()
5151

52-
def iterate_samples(self, collection: Collection[T]) -> Collection[T]:
52+
def iterate_samples(self, collection: Iterable[T]) -> Iterable[T]:
5353
if self is CollectionCheckStrategy.FIRST_ITEM:
54-
if len(collection):
54+
try:
5555
return [next(iter(collection))]
56-
else:
56+
except StopIteration:
5757
return ()
5858
else:
5959
return collection

metaflow/_vendor/typeguard/_decorators.py

Lines changed: 8 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -16,20 +16,18 @@
1616
from ._transformer import TypeguardTransformer
1717
from ._utils import Unset, function_name, get_stacklevel, is_method_of, unset
1818

19+
T_CallableOrType = TypeVar("T_CallableOrType", bound=Callable[..., Any])
20+
1921
if TYPE_CHECKING:
2022
from typeshed.stdlib.types import _Cell
2123

22-
_F = TypeVar("_F")
23-
24-
def typeguard_ignore(f: _F) -> _F:
24+
def typeguard_ignore(f: T_CallableOrType) -> T_CallableOrType:
2525
"""This decorator is a noop during static type-checking."""
2626
return f
2727

2828
else:
2929
from typing import no_type_check as typeguard_ignore # noqa: F401
3030

31-
T_CallableOrType = TypeVar("T_CallableOrType", bound=Callable[..., Any])
32-
3331

3432
def make_cell(value: object) -> _Cell:
3533
return (lambda: value).__closure__[0] # type: ignore[index]
@@ -133,13 +131,11 @@ def typechecked(
133131
typecheck_fail_callback: TypeCheckFailCallback | Unset = unset,
134132
collection_check_strategy: CollectionCheckStrategy | Unset = unset,
135133
debug_instrumentation: bool | Unset = unset,
136-
) -> Callable[[T_CallableOrType], T_CallableOrType]:
137-
...
134+
) -> Callable[[T_CallableOrType], T_CallableOrType]: ...
138135

139136

140137
@overload
141-
def typechecked(target: T_CallableOrType) -> T_CallableOrType:
142-
...
138+
def typechecked(target: T_CallableOrType) -> T_CallableOrType: ...
143139

144140

145141
def typechecked(
@@ -215,9 +211,9 @@ def typechecked(
215211
return target
216212

217213
# Find either the first Python wrapper or the actual function
218-
wrapper_class: type[classmethod[Any, Any, Any]] | type[
219-
staticmethod[Any, Any]
220-
] | None = None
214+
wrapper_class: (
215+
type[classmethod[Any, Any, Any]] | type[staticmethod[Any, Any]] | None
216+
) = None
221217
if isinstance(target, (classmethod, staticmethod)):
222218
wrapper_class = target.__class__
223219
target = target.__func__

metaflow/_vendor/typeguard/_functions.py

Lines changed: 33 additions & 32 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22

33
import sys
44
import warnings
5-
from typing import Any, Callable, NoReturn, TypeVar, overload
5+
from typing import Any, Callable, NoReturn, TypeVar, Union, overload
66

77
from . import _suppression
88
from ._checkers import BINARY_MAGIC_METHODS, check_type_internal
@@ -32,8 +32,7 @@ def check_type(
3232
forward_ref_policy: ForwardRefPolicy = ...,
3333
typecheck_fail_callback: TypeCheckFailCallback | None = ...,
3434
collection_check_strategy: CollectionCheckStrategy = ...,
35-
) -> T:
36-
...
35+
) -> T: ...
3736

3837

3938
@overload
@@ -44,16 +43,15 @@ def check_type(
4443
forward_ref_policy: ForwardRefPolicy = ...,
4544
typecheck_fail_callback: TypeCheckFailCallback | None = ...,
4645
collection_check_strategy: CollectionCheckStrategy = ...,
47-
) -> Any:
48-
...
46+
) -> Any: ...
4947

5048

5149
def check_type(
5250
value: object,
5351
expected_type: Any,
5452
*,
5553
forward_ref_policy: ForwardRefPolicy = TypeCheckConfiguration().forward_ref_policy,
56-
typecheck_fail_callback: (TypeCheckFailCallback | None) = (
54+
typecheck_fail_callback: TypeCheckFailCallback | None = (
5755
TypeCheckConfiguration().typecheck_fail_callback
5856
),
5957
collection_check_strategy: CollectionCheckStrategy = (
@@ -80,7 +78,7 @@ def check_type(
8078
corresponding fields in :class:`TypeCheckConfiguration`.
8179
8280
:param value: value to be checked against ``expected_type``
83-
:param expected_type: a class or generic type instance
81+
:param expected_type: a class or generic type instance, or a tuple of such things
8482
:param forward_ref_policy: see :attr:`TypeCheckConfiguration.forward_ref_policy`
8583
:param typecheck_fail_callback:
8684
see :attr`TypeCheckConfiguration.typecheck_fail_callback`
@@ -90,6 +88,9 @@ def check_type(
9088
:raises TypeCheckError: if there is a type mismatch
9189
9290
"""
91+
if type(expected_type) is tuple:
92+
expected_type = Union[expected_type]
93+
9394
config = TypeCheckConfiguration(
9495
forward_ref_policy=forward_ref_policy,
9596
typecheck_fail_callback=typecheck_fail_callback,
@@ -244,7 +245,7 @@ def check_variable_assignment(
244245
value: object, varname: str, annotation: Any, memo: TypeCheckMemo
245246
) -> Any:
246247
if _suppression.type_checks_suppressed:
247-
return
248+
return value
248249

249250
try:
250251
check_type_internal(value, annotation, memo)
@@ -262,36 +263,36 @@ def check_variable_assignment(
262263
def check_multi_variable_assignment(
263264
value: Any, targets: list[dict[str, Any]], memo: TypeCheckMemo
264265
) -> Any:
265-
if _suppression.type_checks_suppressed:
266-
return
267-
268266
if max(len(target) for target in targets) == 1:
269267
iterated_values = [value]
270268
else:
271269
iterated_values = list(value)
272270

273-
for expected_types in targets:
274-
value_index = 0
275-
for ann_index, (varname, expected_type) in enumerate(expected_types.items()):
276-
if varname.startswith("*"):
277-
varname = varname[1:]
278-
keys_left = len(expected_types) - 1 - ann_index
279-
next_value_index = len(iterated_values) - keys_left
280-
obj: object = iterated_values[value_index:next_value_index]
281-
value_index = next_value_index
282-
else:
283-
obj = iterated_values[value_index]
284-
value_index += 1
285-
286-
try:
287-
check_type_internal(obj, expected_type, memo)
288-
except TypeCheckError as exc:
289-
qualname = qualified_name(obj, add_class_prefix=True)
290-
exc.append_path_element(f"value assigned to {varname} ({qualname})")
291-
if memo.config.typecheck_fail_callback:
292-
memo.config.typecheck_fail_callback(exc, memo)
271+
if not _suppression.type_checks_suppressed:
272+
for expected_types in targets:
273+
value_index = 0
274+
for ann_index, (varname, expected_type) in enumerate(
275+
expected_types.items()
276+
):
277+
if varname.startswith("*"):
278+
varname = varname[1:]
279+
keys_left = len(expected_types) - 1 - ann_index
280+
next_value_index = len(iterated_values) - keys_left
281+
obj: object = iterated_values[value_index:next_value_index]
282+
value_index = next_value_index
293283
else:
294-
raise
284+
obj = iterated_values[value_index]
285+
value_index += 1
286+
287+
try:
288+
check_type_internal(obj, expected_type, memo)
289+
except TypeCheckError as exc:
290+
qualname = qualified_name(obj, add_class_prefix=True)
291+
exc.append_path_element(f"value assigned to {varname} ({qualname})")
292+
if memo.config.typecheck_fail_callback:
293+
memo.config.typecheck_fail_callback(exc, memo)
294+
else:
295+
raise
295296

296297
return iterated_values[0] if len(iterated_values) == 1 else iterated_values
297298

metaflow/_vendor/typeguard/_pytest_plugin.py

Lines changed: 40 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -2,28 +2,45 @@
22

33
import sys
44
import warnings
5-
6-
from pytest import Config, Parser
5+
from typing import TYPE_CHECKING, Any, Literal
76

87
from metaflow._vendor.typeguard._config import CollectionCheckStrategy, ForwardRefPolicy, global_config
98
from metaflow._vendor.typeguard._exceptions import InstrumentationWarning
109
from metaflow._vendor.typeguard._importhook import install_import_hook
1110
from metaflow._vendor.typeguard._utils import qualified_name, resolve_reference
1211

12+
if TYPE_CHECKING:
13+
from pytest import Config, Parser
14+
1315

1416
def pytest_addoption(parser: Parser) -> None:
17+
def add_ini_option(
18+
opt_type: (
19+
Literal["string", "paths", "pathlist", "args", "linelist", "bool"] | None
20+
),
21+
) -> None:
22+
parser.addini(
23+
group.options[-1].names()[0][2:],
24+
group.options[-1].attrs()["help"],
25+
opt_type,
26+
)
27+
1528
group = parser.getgroup("typeguard")
1629
group.addoption(
1730
"--typeguard-packages",
1831
action="store",
1932
help="comma separated name list of packages and modules to instrument for "
2033
"type checking, or :all: to instrument all modules loaded after typeguard",
2134
)
35+
add_ini_option("linelist")
36+
2237
group.addoption(
2338
"--typeguard-debug-instrumentation",
2439
action="store_true",
2540
help="print all instrumented code to stderr",
2641
)
42+
add_ini_option("bool")
43+
2744
group.addoption(
2845
"--typeguard-typecheck-fail-callback",
2946
action="store",
@@ -33,6 +50,8 @@ def pytest_addoption(parser: Parser) -> None:
3350
"handle a TypeCheckError"
3451
),
3552
)
53+
add_ini_option("string")
54+
3655
group.addoption(
3756
"--typeguard-forward-ref-policy",
3857
action="store",
@@ -42,21 +61,31 @@ def pytest_addoption(parser: Parser) -> None:
4261
"annotations"
4362
),
4463
)
64+
add_ini_option("string")
65+
4566
group.addoption(
4667
"--typeguard-collection-check-strategy",
4768
action="store",
4869
choices=list(CollectionCheckStrategy.__members__),
4970
help="determines how thoroughly to check collections (list, dict, etc)",
5071
)
72+
add_ini_option("string")
5173

5274

5375
def pytest_configure(config: Config) -> None:
54-
packages_option = config.getoption("typeguard_packages")
55-
if packages_option:
56-
if packages_option == ":all:":
57-
packages: list[str] | None = None
76+
def getoption(name: str) -> Any:
77+
return config.getoption(name.replace("-", "_")) or config.getini(name)
78+
79+
packages: list[str] | None = []
80+
if packages_option := config.getoption("typeguard_packages"):
81+
packages = [pkg.strip() for pkg in packages_option.split(",")]
82+
elif packages_ini := config.getini("typeguard-packages"):
83+
packages = packages_ini
84+
85+
if packages:
86+
if packages == [":all:"]:
87+
packages = None
5888
else:
59-
packages = [pkg.strip() for pkg in packages_option.split(",")]
6089
already_imported_packages = sorted(
6190
package for package in packages if package in sys.modules
6291
)
@@ -70,11 +99,11 @@ def pytest_configure(config: Config) -> None:
7099

71100
install_import_hook(packages=packages)
72101

73-
debug_option = config.getoption("typeguard_debug_instrumentation")
102+
debug_option = getoption("typeguard-debug-instrumentation")
74103
if debug_option:
75104
global_config.debug_instrumentation = True
76105

77-
fail_callback_option = config.getoption("typeguard_typecheck_fail_callback")
106+
fail_callback_option = getoption("typeguard-typecheck-fail-callback")
78107
if fail_callback_option:
79108
callback = resolve_reference(fail_callback_option)
80109
if not callable(callback):
@@ -85,14 +114,12 @@ def pytest_configure(config: Config) -> None:
85114

86115
global_config.typecheck_fail_callback = callback
87116

88-
forward_ref_policy_option = config.getoption("typeguard_forward_ref_policy")
117+
forward_ref_policy_option = getoption("typeguard-forward-ref-policy")
89118
if forward_ref_policy_option:
90119
forward_ref_policy = ForwardRefPolicy.__members__[forward_ref_policy_option]
91120
global_config.forward_ref_policy = forward_ref_policy
92121

93-
collection_check_strategy_option = config.getoption(
94-
"typeguard_collection_check_strategy"
95-
)
122+
collection_check_strategy_option = getoption("typeguard-collection-check-strategy")
96123
if collection_check_strategy_option:
97124
collection_check_strategy = CollectionCheckStrategy.__members__[
98125
collection_check_strategy_option

metaflow/_vendor/typeguard/_suppression.py

Lines changed: 3 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -20,17 +20,15 @@
2020

2121

2222
@overload
23-
def suppress_type_checks(func: Callable[P, T]) -> Callable[P, T]:
24-
...
23+
def suppress_type_checks(func: Callable[P, T]) -> Callable[P, T]: ...
2524

2625

2726
@overload
28-
def suppress_type_checks() -> ContextManager[None]:
29-
...
27+
def suppress_type_checks() -> ContextManager[None]: ...
3028

3129

3230
def suppress_type_checks(
33-
func: Callable[P, T] | None = None
31+
func: Callable[P, T] | None = None,
3432
) -> Callable[P, T] | ContextManager[None]:
3533
"""
3634
Temporarily suppress all type checking.

0 commit comments

Comments
 (0)