Skip to content

Commit 00f023c

Browse files
committed
work around python/mypy#11612
1 parent d4c50ab commit 00f023c

File tree

12 files changed

+50
-39
lines changed

12 files changed

+50
-39
lines changed

.mypy/baseline.json

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2041,7 +2041,7 @@
20412041
"code": "truthy-bool",
20422042
"column": 24,
20432043
"message": "\"rvalue_type\" has type \"Type\" which does not implement __bool__ or __len__ so it could always be true in boolean context",
2044-
"offset": 160,
2044+
"offset": 140,
20452045
"src": "and rvalue_type",
20462046
"target": "mypy.checker.TypeChecker.check_assignment"
20472047
},
@@ -42258,4 +42258,4 @@
4225842258
"package:mypy",
4225942259
"package:mypyc"
4226042260
]
42261-
}
42261+
}

mypy/checker.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2685,7 +2685,7 @@ class Bar(enum.Enum):
26852685
def __new__(cls, val): ...
26862686
class Baz(int, Foo, Bar, enum.Flag): ...
26872687
"""
2688-
enum_base: Instance | None = None
2688+
enum_base = cast(Optional[Instance], None)
26892689
for base in defn.info.bases:
26902690
if enum_base is None and base.type.is_enum:
26912691
enum_base = base

mypy/modulefinder.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,7 @@
2121
else:
2222
import tomli as tomllib
2323

24-
from typing import Dict, Final, List, NamedTuple, Optional, Tuple, Union
24+
from typing import Dict, Final, List, NamedTuple, Optional, Tuple, Union, cast
2525
from typing_extensions import TypeAlias as _TypeAlias
2626

2727
from mypy import pyinfo
@@ -324,7 +324,7 @@ def _typeshed_has_version(self, module: str) -> bool:
324324
def _find_module_non_stub_helper(
325325
self, components: list[str], pkg_dir: str, ignore_missing_py_typed=False
326326
) -> OnePackageDir | ModuleNotFoundReason:
327-
plausible_match: OnePackageDir | None = None
327+
plausible_match = cast(Optional[OnePackageDir], None)
328328
dir_path = pkg_dir
329329
for index, component in enumerate(components):
330330
dir_path = os.path.join(dir_path, component)

mypy/plugins/attrs.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@
44

55
from collections import defaultdict
66
from functools import reduce
7-
from typing import Final, Iterable, List, Mapping, cast
7+
from typing import Final, Iterable, List, Mapping, Optional, cast
88
from typing_extensions import Literal
99

1010
import mypy.plugin # To avoid circular imports.
@@ -656,7 +656,7 @@ def _parse_converter(
656656
else:
657657
is_attr_converters_optional = False
658658

659-
converter_type: Type | None = None
659+
converter_type = cast(Optional[Type], None)
660660
if isinstance(converter_expr, RefExpr) and converter_expr.node:
661661
if isinstance(converter_expr.node, FuncDef):
662662
if converter_expr.node.type and isinstance(converter_expr.node.type, FunctionLike):
@@ -996,7 +996,7 @@ def _get_expanded_attr_types(
996996
if isinstance(typ, AnyType):
997997
return None
998998
elif isinstance(typ, UnionType):
999-
ret: list[Mapping[str, Type]] | None = []
999+
ret = cast(Optional[List[Mapping[str, Type]]], [])
10001000
for item in typ.relevant_items():
10011001
item = get_proper_type(item)
10021002
item_types = _get_expanded_attr_types(ctx, item, item, parent_typ)

mypy/plugins/dataclasses.py

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

33
from __future__ import annotations
44

5-
from typing import TYPE_CHECKING, Final, Iterator, Literal
5+
from typing import TYPE_CHECKING, Final, Iterator, List, Literal, Optional, cast
66

77
from mypy import errorcodes, message_registry
88
from mypy.expandtype import expand_type, expand_type_by_instance
@@ -996,7 +996,7 @@ def _get_expanded_dataclasses_fields(
996996
if isinstance(typ, AnyType):
997997
return None
998998
elif isinstance(typ, UnionType):
999-
ret: list[CallableType] | None = []
999+
ret = cast(Optional[List[CallableType]], [])
10001000
for item in typ.relevant_items():
10011001
item = get_proper_type(item)
10021002
item_types = _get_expanded_dataclasses_fields(ctx, item, item, parent_typ)

mypy/semanal.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6173,7 +6173,7 @@ def _get_node_for_class_scoped_import(
61736173
# mypyc is absolutely convinced that `symbol_node` narrows to a Var in the following,
61746174
# when it can also be a FuncBase. Once fixed, `f` in the following can be removed.
61756175
# See also https://github.com/mypyc/mypyc/issues/892
6176-
f: Callable[[object], Any] = lambda x: x
6176+
f = cast(Callable[[object], Any], lambda x: x)
61776177
if isinstance(f(symbol_node), (Decorator, FuncBase, Var)):
61786178
# For imports in class scope, we construct a new node to represent the symbol and
61796179
# set its `info` attribute to `self.type`.

mypy/server/update.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -118,7 +118,7 @@
118118
import re
119119
import sys
120120
import time
121-
from typing import Callable, Final, NamedTuple, Sequence, Union
121+
from typing import Callable, Final, NamedTuple, Optional, Sequence, Union, cast
122122
from typing_extensions import TypeAlias as _TypeAlias
123123

124124
from mypy.build import (
@@ -1112,7 +1112,7 @@ def not_found() -> None:
11121112
components = rest.split(".")
11131113
else:
11141114
components = []
1115-
node: SymbolNode | None = modules[module]
1115+
node = cast(Optional[SymbolNode], modules[module])
11161116
file: MypyFile | None = None
11171117
active_class = None
11181118
for c in components:

mypy/test/testfinegrained.py

Lines changed: 26 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,7 @@
1717
import os
1818
import re
1919
import unittest
20-
from typing import Any
20+
from typing import Any, Dict, cast
2121

2222
import pytest
2323

@@ -309,15 +309,18 @@ def maybe_suggest(self, step: int, server: Server, src: str, tmp_dir: str) -> li
309309
use_fixme = m.group(1) if m else None
310310
m = re.match("--max-guesses=([0-9]+)", flags)
311311
max_guesses = int(safe(m.group(1))) if m else None
312-
res: dict[str, Any] = server.cmd_suggest(
313-
target.strip(),
314-
json=json,
315-
no_any=no_any,
316-
no_errors=no_errors,
317-
flex_any=flex_any,
318-
use_fixme=use_fixme,
319-
callsites=callsites,
320-
max_guesses=max_guesses,
312+
res = cast(
313+
Dict[str, Any],
314+
server.cmd_suggest(
315+
target.strip(),
316+
json=json,
317+
no_any=no_any,
318+
no_errors=no_errors,
319+
flex_any=flex_any,
320+
use_fixme=use_fixme,
321+
callsites=callsites,
322+
max_guesses=max_guesses,
323+
),
321324
)
322325
val = res["error"] if "error" in res else res["out"] + res["err"]
323326
if json:
@@ -348,16 +351,19 @@ def maybe_inspect(self, step: int, server: Server, src: str) -> list[str]:
348351
include_object_attrs = "--include-object-attrs" in flags
349352
union_attrs = "--union-attrs" in flags
350353
force_reload = "--force-reload" in flags
351-
res: dict[str, Any] = server.cmd_inspect(
352-
show,
353-
location,
354-
verbosity=verbosity,
355-
limit=limit,
356-
include_span=include_span,
357-
include_kind=include_kind,
358-
include_object_attrs=include_object_attrs,
359-
union_attrs=union_attrs,
360-
force_reload=force_reload,
354+
res = cast(
355+
Dict[str, Any],
356+
server.cmd_inspect(
357+
show,
358+
location,
359+
verbosity=verbosity,
360+
limit=limit,
361+
include_span=include_span,
362+
include_kind=include_kind,
363+
include_object_attrs=include_object_attrs,
364+
union_attrs=union_attrs,
365+
force_reload=force_reload,
366+
),
361367
)
362368
val = res["error"] if "error" in res else res["out"] + res["err"]
363369
output.extend(val.strip().split("\n"))

mypy/tvar_scope.py

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,7 @@
11
from __future__ import annotations
22

3+
from typing import Optional, cast
4+
35
from mypy.nodes import (
46
ParamSpecExpr,
57
SymbolTableNode,
@@ -51,7 +53,7 @@ def __init__(
5153

5254
def get_function_scope(self) -> TypeVarLikeScope | None:
5355
"""Get the nearest parent that's a function scope, not a class scope"""
54-
it: TypeVarLikeScope | None = self
56+
it = cast(Optional[TypeVarLikeScope], self)
5557
while it is not None and it.is_class_scope:
5658
it = it.parent
5759
return it

mypy/types.py

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@
1616
Iterable,
1717
NamedTuple,
1818
NewType,
19+
Optional,
1920
Sequence,
2021
TypeVar,
2122
Union,
@@ -2274,7 +2275,7 @@ def with_normalized_var_args(self) -> Self:
22742275
types_suffix = self.arg_types[var_arg_index + 1 :]
22752276
kinds_suffix = self.arg_kinds[var_arg_index + 1 :]
22762277
names_suffix = self.arg_names[var_arg_index + 1 :]
2277-
no_name: str | None = None # to silence mypy
2278+
no_name = cast(Union[str, None], None) # to silence mypy
22782279

22792280
# Now we have something non-trivial to do.
22802281
if unpack_index is None:
@@ -3854,7 +3855,7 @@ def flatten_nested_unions(
38543855

38553856

38563857
def find_unpack_in_list(items: Sequence[Type]) -> int | None:
3857-
unpack_index: int | None = None
3858+
unpack_index = cast(Optional[int], None)
38583859
for i, item in enumerate(items):
38593860
if isinstance(item, UnpackType):
38603861
# We cannot fail here, so we must check this in an earlier

mypyc/irbuild/expression.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@
77
from __future__ import annotations
88

99
import math
10-
from typing import Callable, Sequence
10+
from typing import Callable, Optional, Sequence, cast
1111

1212
from mypy.nodes import (
1313
ARG_POS,
@@ -984,7 +984,7 @@ def _visit_display(
984984
else:
985985
accepted_items.append((False, builder.accept(item)))
986986

987-
result: Value | None = None
987+
result = cast(Optional[Value], None)
988988
initial_items = []
989989
for starred, value in accepted_items:
990990
if result is None and not starred and is_list:

mypyc/transform/exceptions.py

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,8 @@
1111

1212
from __future__ import annotations
1313

14+
from typing import Optional, cast
15+
1416
from mypyc.ir.func_ir import FuncIR
1517
from mypyc.ir.ops import (
1618
ERR_ALWAYS,
@@ -43,7 +45,7 @@ def insert_exception_handling(ir: FuncIR) -> None:
4345
# Generate error block if any ops may raise an exception. If an op
4446
# fails without its own error handler, we'll branch to this
4547
# block. The block just returns an error value.
46-
error_label: BasicBlock | None = None
48+
error_label = cast(Optional[BasicBlock], None)
4749
for block in ir.blocks:
4850
adjust_error_kinds(block)
4951
if error_label is None and any(op.can_raise() for op in block.ops):

0 commit comments

Comments
 (0)