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

Use PEP 585 collections #18378

Merged
merged 1 commit into from
Dec 30, 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
4 changes: 2 additions & 2 deletions misc/analyze_cache.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,12 +7,12 @@
import os.path
from collections import Counter
from collections.abc import Iterable
from typing import Any, Dict, Final
from typing import Any, Final
from typing_extensions import TypeAlias as _TypeAlias

ROOT: Final = ".mypy_cache/3.5"

JsonDict: _TypeAlias = Dict[str, Any]
JsonDict: _TypeAlias = dict[str, Any]


class CacheData:
Expand Down
4 changes: 2 additions & 2 deletions misc/incremental_checker.py
Original file line number Diff line number Diff line change
Expand Up @@ -44,15 +44,15 @@
import textwrap
import time
from argparse import ArgumentParser, Namespace, RawDescriptionHelpFormatter
from typing import Any, Dict, Final
from typing import Any, Final
from typing_extensions import TypeAlias as _TypeAlias

CACHE_PATH: Final = ".incremental_checker_cache.json"
MYPY_REPO_URL: Final = "https://github.com/python/mypy.git"
MYPY_TARGET_FILE: Final = "mypy"
DAEMON_CMD: Final = ["python3", "-m", "mypy.dmypy"]

JsonDict: _TypeAlias = Dict[str, Any]
JsonDict: _TypeAlias = dict[str, Any]


def print_offset(text: str, indent_length: int = 4) -> None:
Expand Down
4 changes: 2 additions & 2 deletions mypy/binder.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
from collections import defaultdict
from collections.abc import Iterator
from contextlib import contextmanager
from typing import DefaultDict, List, NamedTuple, Optional, Tuple, Union
from typing import NamedTuple, Optional, Union
from typing_extensions import TypeAlias as _TypeAlias

from mypy.erasetype import remove_instance_last_known_values
Expand Down Expand Up @@ -59,7 +59,7 @@ def __repr__(self) -> str:
return f"Frame({self.id}, {self.types}, {self.unreachable}, {self.conditional_frame})"


Assigns = DefaultDict[Expression, List[Tuple[Type, Optional[Type]]]]
Assigns = defaultdict[Expression, list[tuple[Type, Optional[Type]]]]


class ConditionalTypeBinder:
Expand Down
3 changes: 1 addition & 2 deletions mypy/build.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,6 @@
Any,
Callable,
ClassVar,
Dict,
Final,
NamedTuple,
NoReturn,
Expand Down Expand Up @@ -118,7 +117,7 @@
}


Graph: _TypeAlias = Dict[str, "State"]
Graph: _TypeAlias = dict[str, "State"]


# TODO: Get rid of BuildResult. We might as well return a BuildManager.
Expand Down
6 changes: 2 additions & 4 deletions mypy/checker.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,12 +9,10 @@
from typing import (
AbstractSet,
Callable,
Dict,
Final,
Generic,
NamedTuple,
Optional,
Tuple,
TypeVar,
Union,
cast,
Expand Down Expand Up @@ -265,7 +263,7 @@ class FineGrainedDeferredNode(NamedTuple):
# (such as two references to the same variable). TODO: it would
# probably be better to have the dict keyed by the nodes' literal_hash
# field instead.
TypeMap: _TypeAlias = Optional[Dict[Expression, Type]]
TypeMap: _TypeAlias = Optional[dict[Expression, Type]]


# An object that represents either a precise type or a type with an upper bound;
Expand Down Expand Up @@ -7813,7 +7811,7 @@ def conditional_types_to_typemaps(
assert typ is not None
maps.append({expr: typ})

return cast(Tuple[TypeMap, TypeMap], tuple(maps))
return cast(tuple[TypeMap, TypeMap], tuple(maps))


def gen_unique_name(base: str, table: SymbolTable) -> str:
Expand Down
4 changes: 2 additions & 2 deletions mypy/checkexpr.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
from collections import defaultdict
from collections.abc import Iterable, Iterator, Sequence
from contextlib import contextmanager
from typing import Callable, ClassVar, Final, List, Optional, cast
from typing import Callable, ClassVar, Final, Optional, cast
from typing_extensions import TypeAlias as _TypeAlias, assert_never, overload

import mypy.checker
Expand Down Expand Up @@ -1966,7 +1966,7 @@ def infer_arg_types_in_context(
if not t:
res[i] = self.accept(args[i])
assert all(tp is not None for tp in res)
return cast(List[Type], res)
return cast(list[Type], res)

def infer_function_type_arguments_using_context(
self, callable: CallableType, error_context: Context
Expand Down
6 changes: 3 additions & 3 deletions mypy/checkstrformat.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@

import re
from re import Match, Pattern
from typing import TYPE_CHECKING, Callable, Dict, Final, Tuple, Union, cast
from typing import TYPE_CHECKING, Callable, Final, Union, cast
from typing_extensions import TypeAlias as _TypeAlias

import mypy.errorcodes as codes
Expand Down Expand Up @@ -70,8 +70,8 @@
from mypy.typeops import custom_special_method

FormatStringExpr: _TypeAlias = Union[StrExpr, BytesExpr]
Checkers: _TypeAlias = Tuple[Callable[[Expression], None], Callable[[Type], bool]]
MatchMap: _TypeAlias = Dict[Tuple[int, int], Match[str]] # span -> match
Checkers: _TypeAlias = tuple[Callable[[Expression], None], Callable[[Type], bool]]
MatchMap: _TypeAlias = dict[tuple[int, int], Match[str]] # span -> match


def compile_format_re() -> Pattern[str]:
Expand Down
4 changes: 2 additions & 2 deletions mypy/config_parser.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,14 +16,14 @@
import tomli as tomllib

from collections.abc import Iterable, Mapping, MutableMapping, Sequence
from typing import Any, Callable, Dict, Final, List, TextIO, Tuple, Union
from typing import Any, Callable, Final, TextIO, Union
from typing_extensions import TypeAlias as _TypeAlias

from mypy import defaults
from mypy.options import PER_MODULE_OPTIONS, Options

_CONFIG_VALUE_TYPES: _TypeAlias = Union[
str, bool, int, float, Dict[str, str], List[str], Tuple[int, int]
str, bool, int, float, dict[str, str], list[str], tuple[int, int]
]
_INI_PARSER_CALLABLE: _TypeAlias = Callable[[Any], _CONFIG_VALUE_TYPES]

Expand Down
4 changes: 2 additions & 2 deletions mypy/constraints.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
from __future__ import annotations

from collections.abc import Iterable, Sequence
from typing import TYPE_CHECKING, Final, List
from typing import TYPE_CHECKING, Final

import mypy.subtypes
import mypy.typeops
Expand Down Expand Up @@ -627,7 +627,7 @@ def visit_uninhabited_type(self, t: UninhabitedType) -> bool:
return False


class ConstraintBuilderVisitor(TypeVisitor[List[Constraint]]):
class ConstraintBuilderVisitor(TypeVisitor[list[Constraint]]):
"""Visitor class for inferring type constraints."""

# The type that is compared against a template
Expand Down
8 changes: 4 additions & 4 deletions mypy/dmypy_server.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@
import traceback
from collections.abc import Sequence
from contextlib import redirect_stderr, redirect_stdout
from typing import AbstractSet, Any, Callable, Final, List, Tuple
from typing import AbstractSet, Any, Callable, Final
from typing_extensions import TypeAlias as _TypeAlias

import mypy.build
Expand Down Expand Up @@ -162,9 +162,9 @@ def ignore_suppressed_imports(module: str) -> bool:
return module.startswith("encodings.")


ModulePathPair: _TypeAlias = Tuple[str, str]
ModulePathPairs: _TypeAlias = List[ModulePathPair]
ChangesAndRemovals: _TypeAlias = Tuple[ModulePathPairs, ModulePathPairs]
ModulePathPair: _TypeAlias = tuple[str, str]
ModulePathPairs: _TypeAlias = list[ModulePathPair]
ChangesAndRemovals: _TypeAlias = tuple[ModulePathPairs, ModulePathPairs]


class Server:
Expand Down
6 changes: 3 additions & 3 deletions mypy/errors.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
import traceback
from collections import defaultdict
from collections.abc import Iterable
from typing import Callable, Final, NoReturn, Optional, TextIO, Tuple, TypeVar
from typing import Callable, Final, NoReturn, Optional, TextIO, TypeVar
from typing_extensions import Literal, TypeAlias as _TypeAlias

from mypy import errorcodes as codes
Expand Down Expand Up @@ -152,7 +152,7 @@ def __init__(

# Type used internally to represent errors:
# (path, line, column, end_line, end_column, severity, message, allow_dups, code)
ErrorTuple: _TypeAlias = Tuple[
ErrorTuple: _TypeAlias = tuple[
Optional[str], int, int, int, int, str, str, bool, Optional[ErrorCode]
]

Expand Down Expand Up @@ -1328,7 +1328,7 @@ def __init__(


# (file_path, line, column)
_ErrorLocation = Tuple[str, int, int]
_ErrorLocation = tuple[str, int, int]


def create_errors(error_tuples: list[ErrorTuple]) -> list[MypyError]:
Expand Down
14 changes: 7 additions & 7 deletions mypy/fastparse.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
import sys
import warnings
from collections.abc import Sequence
from typing import Any, Callable, Final, List, Optional, TypeVar, Union, cast
from typing import Any, Callable, Final, Optional, TypeVar, Union, cast
from typing_extensions import Literal, overload

from mypy import defaults, errorcodes as codes, message_registry
Expand Down Expand Up @@ -425,7 +425,7 @@ def translate_opt_expr_list(self, l: Sequence[AST | None]) -> list[Expression |
return res

def translate_expr_list(self, l: Sequence[AST]) -> list[Expression]:
return cast(List[Expression], self.translate_opt_expr_list(l))
return cast(list[Expression], self.translate_opt_expr_list(l))

def get_lineno(self, node: ast3.expr | ast3.stmt) -> int:
if (
Expand Down Expand Up @@ -668,7 +668,7 @@ def fix_function_overloads(self, stmts: list[Statement]) -> list[Statement]:
current_overload.append(last_if_overload)
last_if_stmt, last_if_overload = None, None
if isinstance(if_block_with_overload.body[-1], OverloadedFuncDef):
skipped_if_stmts.extend(cast(List[IfStmt], if_block_with_overload.body[:-1]))
skipped_if_stmts.extend(cast(list[IfStmt], if_block_with_overload.body[:-1]))
current_overload.extend(if_block_with_overload.body[-1].items)
else:
current_overload.append(
Expand Down Expand Up @@ -715,7 +715,7 @@ def fix_function_overloads(self, stmts: list[Statement]) -> list[Statement]:
last_if_stmt_overload_name = None
if if_block_with_overload is not None:
skipped_if_stmts.extend(
cast(List[IfStmt], if_block_with_overload.body[:-1])
cast(list[IfStmt], if_block_with_overload.body[:-1])
)
last_if_overload = cast(
Union[Decorator, FuncDef, OverloadedFuncDef],
Expand Down Expand Up @@ -939,7 +939,7 @@ def do_func_def(
self.errors, line=lineno, override_column=n.col_offset
).translate_expr_list(func_type_ast.argtypes)
# Use a cast to work around `list` invariance
arg_types = cast(List[Optional[Type]], translated_args)
arg_types = cast(list[Optional[Type]], translated_args)
return_type = TypeConverter(self.errors, line=lineno).visit(func_type_ast.returns)

# add implicit self type
Expand Down Expand Up @@ -1051,7 +1051,7 @@ def transform_args(
) -> list[Argument]:
new_args = []
names: list[ast3.arg] = []
posonlyargs = getattr(args, "posonlyargs", cast(List[ast3.arg], []))
posonlyargs = getattr(args, "posonlyargs", cast(list[ast3.arg], []))
args_args = posonlyargs + args.args
args_defaults = args.defaults
num_no_defaults = len(args_args) - len(args_defaults)
Expand Down Expand Up @@ -1589,7 +1589,7 @@ def visit_Call(self, n: Call) -> CallExpr:
self.visit(n.func),
arg_types,
arg_kinds,
cast("List[Optional[str]]", [None] * len(args)) + keyword_names,
cast("list[Optional[str]]", [None] * len(args)) + keyword_names,
)
return self.set_line(e, n)

Expand Down
4 changes: 2 additions & 2 deletions mypy/literals.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
from __future__ import annotations

from collections.abc import Iterable
from typing import Any, Final, Optional, Tuple
from typing import Any, Final, Optional
from typing_extensions import TypeAlias as _TypeAlias

from mypy.nodes import (
Expand Down Expand Up @@ -129,7 +129,7 @@ def literal(e: Expression) -> int:
return LITERAL_NO


Key: _TypeAlias = Tuple[Any, ...]
Key: _TypeAlias = tuple[Any, ...]


def subkeys(key: Key) -> Iterable[Key]:
Expand Down
4 changes: 2 additions & 2 deletions mypy/memprofile.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@
import sys
from collections import defaultdict
from collections.abc import Iterable
from typing import Dict, cast
from typing import cast

from mypy.nodes import FakeInfo, Node
from mypy.types import Type
Expand Down Expand Up @@ -109,7 +109,7 @@ def visit(o: object) -> None:
# Processing these would cause a crash.
continue
if type(obj) in (dict, defaultdict):
for key, val in cast(Dict[object, object], obj).items():
for key, val in cast(dict[object, object], obj).items():
visit(key)
visit(val)
if type(obj) in (list, tuple, set):
Expand Down
4 changes: 2 additions & 2 deletions mypy/messages.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@
from collections.abc import Collection, Iterable, Iterator, Sequence
from contextlib import contextmanager
from textwrap import dedent
from typing import Any, Callable, Final, List, cast
from typing import Any, Callable, Final, cast

import mypy.typeops
from mypy import errorcodes as codes, message_registry
Expand Down Expand Up @@ -955,7 +955,7 @@ def too_few_arguments(
msg = "Missing positional arguments"
callee_name = callable_name(callee)
if callee_name is not None and diff and all(d is not None for d in diff):
args = '", "'.join(cast(List[str], diff))
args = '", "'.join(cast(list[str], diff))
msg += f' "{args}" in call to {callee_name}'
else:
msg = "Too few arguments" + for_function(callee)
Expand Down
8 changes: 4 additions & 4 deletions mypy/modulefinder.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@
import subprocess
import sys
from enum import Enum, unique
from typing import Dict, Final, List, Optional, Tuple, Union
from typing import Final, Optional, Union
from typing_extensions import TypeAlias as _TypeAlias

from mypy import pyinfo
Expand Down Expand Up @@ -53,11 +53,11 @@ def asdict(self) -> dict[str, tuple[str, ...]]:


# Package dirs are a two-tuple of path to search and whether to verify the module
OnePackageDir = Tuple[str, bool]
PackageDirs = List[OnePackageDir]
OnePackageDir = tuple[str, bool]
PackageDirs = list[OnePackageDir]

# Minimum and maximum Python versions for modules in stdlib as (major, minor)
StdlibVersions: _TypeAlias = Dict[str, Tuple[Tuple[int, int], Optional[Tuple[int, int]]]]
StdlibVersions: _TypeAlias = dict[str, tuple[tuple[int, int], Optional[tuple[int, int]]]]

PYTHON_EXTENSIONS: Final = [".pyi", ".py"]

Expand Down
Loading
Loading