Skip to content

Commit

Permalink
work around python#11612
Browse files Browse the repository at this point in the history
  • Loading branch information
KotlinIsland committed Nov 13, 2023
1 parent 9c0d426 commit 4956f80
Show file tree
Hide file tree
Showing 12 changed files with 50 additions and 39 deletions.
4 changes: 2 additions & 2 deletions .mypy/baseline.json
Original file line number Diff line number Diff line change
Expand Up @@ -2041,7 +2041,7 @@
"code": "truthy-bool",
"column": 24,
"message": "\"rvalue_type\" has type \"Type\" which does not implement __bool__ or __len__ so it could always be true in boolean context",
"offset": 160,
"offset": 140,
"src": "and rvalue_type",
"target": "mypy.checker.TypeChecker.check_assignment"
},
Expand Down Expand Up @@ -42258,4 +42258,4 @@
"package:mypy",
"package:mypyc"
]
}
}
2 changes: 1 addition & 1 deletion mypy/checker.py
Original file line number Diff line number Diff line change
Expand Up @@ -2685,7 +2685,7 @@ class Bar(enum.Enum):
def __new__(cls, val): ...
class Baz(int, Foo, Bar, enum.Flag): ...
"""
enum_base: Instance | None = None
enum_base = cast(Optional[Instance], None)
for base in defn.info.bases:
if enum_base is None and base.type.is_enum:
enum_base = base
Expand Down
4 changes: 2 additions & 2 deletions mypy/modulefinder.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@
else:
import tomli as tomllib

from typing import Dict, Final, List, NamedTuple, Optional, Tuple, Union
from typing import Dict, Final, List, NamedTuple, Optional, Tuple, Union, cast
from typing_extensions import TypeAlias as _TypeAlias

from mypy import pyinfo
Expand Down Expand Up @@ -324,7 +324,7 @@ def _typeshed_has_version(self, module: str) -> bool:
def _find_module_non_stub_helper(
self, components: list[str], pkg_dir: str, ignore_missing_py_typed=False
) -> OnePackageDir | ModuleNotFoundReason:
plausible_match: OnePackageDir | None = None
plausible_match = cast(Optional[OnePackageDir], None)
dir_path = pkg_dir
for index, component in enumerate(components):
dir_path = os.path.join(dir_path, component)
Expand Down
6 changes: 3 additions & 3 deletions mypy/plugins/attrs.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@

from collections import defaultdict
from functools import reduce
from typing import Final, Iterable, List, Mapping, cast
from typing import Final, Iterable, List, Mapping, Optional, cast
from typing_extensions import Literal

import mypy.plugin # To avoid circular imports.
Expand Down Expand Up @@ -656,7 +656,7 @@ def _parse_converter(
else:
is_attr_converters_optional = False

converter_type: Type | None = None
converter_type = cast(Optional[Type], None)
if isinstance(converter_expr, RefExpr) and converter_expr.node:
if isinstance(converter_expr.node, FuncDef):
if converter_expr.node.type and isinstance(converter_expr.node.type, FunctionLike):
Expand Down Expand Up @@ -996,7 +996,7 @@ def _get_expanded_attr_types(
if isinstance(typ, AnyType):
return None
elif isinstance(typ, UnionType):
ret: list[Mapping[str, Type]] | None = []
ret = cast(Optional[List[Mapping[str, Type]]], [])
for item in typ.relevant_items():
item = get_proper_type(item)
item_types = _get_expanded_attr_types(ctx, item, item, parent_typ)
Expand Down
4 changes: 2 additions & 2 deletions mypy/plugins/dataclasses.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

from __future__ import annotations

from typing import TYPE_CHECKING, Final, Iterator, Literal
from typing import TYPE_CHECKING, Final, Iterator, List, Literal, Optional, cast

from mypy import errorcodes, message_registry
from mypy.expandtype import expand_type, expand_type_by_instance
Expand Down Expand Up @@ -996,7 +996,7 @@ def _get_expanded_dataclasses_fields(
if isinstance(typ, AnyType):
return None
elif isinstance(typ, UnionType):
ret: list[CallableType] | None = []
ret = cast(Optional[List[CallableType]], [])
for item in typ.relevant_items():
item = get_proper_type(item)
item_types = _get_expanded_dataclasses_fields(ctx, item, item, parent_typ)
Expand Down
2 changes: 1 addition & 1 deletion mypy/semanal.py
Original file line number Diff line number Diff line change
Expand Up @@ -6173,7 +6173,7 @@ def _get_node_for_class_scoped_import(
# mypyc is absolutely convinced that `symbol_node` narrows to a Var in the following,
# when it can also be a FuncBase. Once fixed, `f` in the following can be removed.
# See also https://github.com/mypyc/mypyc/issues/892
f: Callable[[object], Any] = lambda x: x
f = cast(Callable[[object], Any], lambda x: x)
if isinstance(f(symbol_node), (Decorator, FuncBase, Var)):
# For imports in class scope, we construct a new node to represent the symbol and
# set its `info` attribute to `self.type`.
Expand Down
4 changes: 2 additions & 2 deletions mypy/server/update.py
Original file line number Diff line number Diff line change
Expand Up @@ -118,7 +118,7 @@
import re
import sys
import time
from typing import Callable, Final, NamedTuple, Sequence, Union
from typing import Callable, Final, NamedTuple, Optional, Sequence, Union, cast
from typing_extensions import TypeAlias as _TypeAlias

from mypy.build import (
Expand Down Expand Up @@ -1112,7 +1112,7 @@ def not_found() -> None:
components = rest.split(".")
else:
components = []
node: SymbolNode | None = modules[module]
node = cast(Optional[SymbolNode], modules[module])
file: MypyFile | None = None
active_class = None
for c in components:
Expand Down
46 changes: 26 additions & 20 deletions mypy/test/testfinegrained.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@
import os
import re
import unittest
from typing import Any
from typing import Any, Dict, cast

import pytest

Expand Down Expand Up @@ -309,15 +309,18 @@ def maybe_suggest(self, step: int, server: Server, src: str, tmp_dir: str) -> li
use_fixme = m.group(1) if m else None
m = re.match("--max-guesses=([0-9]+)", flags)
max_guesses = int(safe(m.group(1))) if m else None
res: dict[str, Any] = server.cmd_suggest(
target.strip(),
json=json,
no_any=no_any,
no_errors=no_errors,
flex_any=flex_any,
use_fixme=use_fixme,
callsites=callsites,
max_guesses=max_guesses,
res = cast(
Dict[str, Any],
server.cmd_suggest(
target.strip(),
json=json,
no_any=no_any,
no_errors=no_errors,
flex_any=flex_any,
use_fixme=use_fixme,
callsites=callsites,
max_guesses=max_guesses,
),
)
val = res["error"] if "error" in res else res["out"] + res["err"]
if json:
Expand Down Expand Up @@ -348,16 +351,19 @@ def maybe_inspect(self, step: int, server: Server, src: str) -> list[str]:
include_object_attrs = "--include-object-attrs" in flags
union_attrs = "--union-attrs" in flags
force_reload = "--force-reload" in flags
res: dict[str, Any] = server.cmd_inspect(
show,
location,
verbosity=verbosity,
limit=limit,
include_span=include_span,
include_kind=include_kind,
include_object_attrs=include_object_attrs,
union_attrs=union_attrs,
force_reload=force_reload,
res = cast(
Dict[str, Any],
server.cmd_inspect(
show,
location,
verbosity=verbosity,
limit=limit,
include_span=include_span,
include_kind=include_kind,
include_object_attrs=include_object_attrs,
union_attrs=union_attrs,
force_reload=force_reload,
),
)
val = res["error"] if "error" in res else res["out"] + res["err"]
output.extend(val.strip().split("\n"))
Expand Down
4 changes: 3 additions & 1 deletion mypy/tvar_scope.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
from __future__ import annotations

from typing import Optional, cast

from mypy.nodes import (
ParamSpecExpr,
SymbolTableNode,
Expand Down Expand Up @@ -51,7 +53,7 @@ def __init__(

def get_function_scope(self) -> TypeVarLikeScope | None:
"""Get the nearest parent that's a function scope, not a class scope"""
it: TypeVarLikeScope | None = self
it = cast(Optional[TypeVarLikeScope], self)
while it is not None and it.is_class_scope:
it = it.parent
return it
Expand Down
5 changes: 3 additions & 2 deletions mypy/types.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
Iterable,
NamedTuple,
NewType,
Optional,
Sequence,
TypeVar,
Union,
Expand Down Expand Up @@ -2274,7 +2275,7 @@ def with_normalized_var_args(self) -> Self:
types_suffix = self.arg_types[var_arg_index + 1 :]
kinds_suffix = self.arg_kinds[var_arg_index + 1 :]
names_suffix = self.arg_names[var_arg_index + 1 :]
no_name: str | None = None # to silence mypy
no_name = cast(Union[str, None], None) # to silence mypy

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


def find_unpack_in_list(items: Sequence[Type]) -> int | None:
unpack_index: int | None = None
unpack_index = cast(Optional[int], None)
for i, item in enumerate(items):
if isinstance(item, UnpackType):
# We cannot fail here, so we must check this in an earlier
Expand Down
4 changes: 2 additions & 2 deletions mypyc/irbuild/expression.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
from __future__ import annotations

import math
from typing import Callable, Sequence
from typing import Callable, Optional, Sequence, cast

from mypy.nodes import (
ARG_POS,
Expand Down Expand Up @@ -984,7 +984,7 @@ def _visit_display(
else:
accepted_items.append((False, builder.accept(item)))

result: Value | None = None
result = cast(Optional[Value], None)
initial_items = []
for starred, value in accepted_items:
if result is None and not starred and is_list:
Expand Down
4 changes: 3 additions & 1 deletion mypyc/transform/exceptions.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,8 @@

from __future__ import annotations

from typing import Optional, cast

from mypyc.ir.func_ir import FuncIR
from mypyc.ir.ops import (
ERR_ALWAYS,
Expand Down Expand Up @@ -43,7 +45,7 @@ def insert_exception_handling(ir: FuncIR) -> None:
# Generate error block if any ops may raise an exception. If an op
# fails without its own error handler, we'll branch to this
# block. The block just returns an error value.
error_label: BasicBlock | None = None
error_label = cast(Optional[BasicBlock], None)
for block in ir.blocks:
adjust_error_kinds(block)
if error_label is None and any(op.can_raise() for op in block.ops):
Expand Down

0 comments on commit 4956f80

Please sign in to comment.