diff --git a/mypy/binder.py b/mypy/binder.py index a83e65276ff4..872b58c4bae0 100644 --- a/mypy/binder.py +++ b/mypy/binder.py @@ -3,7 +3,7 @@ from collections import defaultdict from collections.abc import Iterator from contextlib import contextmanager -from typing import NamedTuple, Optional, Union +from typing import NamedTuple from typing_extensions import TypeAlias as _TypeAlias from mypy.erasetype import remove_instance_last_known_values @@ -39,7 +39,7 @@ ) from mypy.typevars import fill_typevars_with_any -BindableExpression: _TypeAlias = Union[IndexExpr, MemberExpr, NameExpr] +BindableExpression: _TypeAlias = IndexExpr | MemberExpr | NameExpr class CurrentType(NamedTuple): @@ -81,7 +81,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, Type | None]]] class ConditionalTypeBinder: diff --git a/mypy/cache.py b/mypy/cache.py index ad12fd96f1fa..c1b1aba8c0ca 100644 --- a/mypy/cache.py +++ b/mypy/cache.py @@ -48,7 +48,7 @@ from __future__ import annotations from collections.abc import Sequence -from typing import Any, Final, Union +from typing import Any, Final from typing_extensions import TypeAlias as _TypeAlias from librt.internal import ( @@ -391,7 +391,7 @@ def write_str_opt_list(data: WriteBuffer, value: list[str | None]) -> None: write_str_opt(data, item) -JsonValue: _TypeAlias = Union[None, int, str, bool, list["JsonValue"], dict[str, "JsonValue"]] +JsonValue: _TypeAlias = None | int | str | bool | list["JsonValue"] | dict[str, "JsonValue"] def read_json_value(data: ReadBuffer) -> JsonValue: diff --git a/mypy/checker.py b/mypy/checker.py index ad7eb3d35568..440d0175bc62 100644 --- a/mypy/checker.py +++ b/mypy/checker.py @@ -6,18 +6,7 @@ from collections import defaultdict from collections.abc import Iterable, Iterator, Mapping, Sequence, Set as AbstractSet from contextlib import ExitStack, contextmanager -from typing import ( - Callable, - Final, - Generic, - Literal, - NamedTuple, - Optional, - TypeVar, - Union, - cast, - overload, -) +from typing import Callable, Final, Generic, Literal, NamedTuple, TypeVar, cast, overload from typing_extensions import TypeAlias as _TypeAlias, TypeGuard import mypy.checkexpr @@ -249,8 +238,8 @@ # Maximum length of fixed tuple types inferred when narrowing from variadic tuples. MAX_PRECISE_TUPLE_SIZE: Final = 8 -DeferredNodeType: _TypeAlias = Union[FuncDef, OverloadedFuncDef, Decorator] -FineGrainedDeferredNodeType: _TypeAlias = Union[FuncDef, MypyFile, OverloadedFuncDef] +DeferredNodeType: _TypeAlias = FuncDef | OverloadedFuncDef | Decorator +FineGrainedDeferredNodeType: _TypeAlias = FuncDef | MypyFile | OverloadedFuncDef # A node which is postponed to be processed during the next pass. @@ -283,7 +272,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 = dict[Expression, Type] | None # Keeps track of partial types in a single scope. In fine-grained incremental diff --git a/mypy/checkexpr.py b/mypy/checkexpr.py index 03ebc5058cee..4e3be52ef60c 100644 --- a/mypy/checkexpr.py +++ b/mypy/checkexpr.py @@ -8,7 +8,7 @@ from collections import defaultdict from collections.abc import Iterable, Iterator, Sequence from contextlib import contextmanager, nullcontext -from typing import Callable, ClassVar, Final, Optional, cast, overload +from typing import Callable, ClassVar, Final, cast, overload from typing_extensions import TypeAlias as _TypeAlias, assert_never import mypy.checker @@ -217,7 +217,7 @@ # Type of callback user for checking individual function arguments. See # check_args() below for details. ArgChecker: _TypeAlias = Callable[ - [Type, Type, ArgKind, Type, int, int, CallableType, Optional[Type], Context, Context], None + [Type, Type, ArgKind, Type, int, int, CallableType, Type | None, Context, Context], None ] # Maximum nesting level for math union in overloads, setting this to large values diff --git a/mypy/checkstrformat.py b/mypy/checkstrformat.py index 45075bd37552..7c52ae9eec4d 100644 --- a/mypy/checkstrformat.py +++ b/mypy/checkstrformat.py @@ -14,7 +14,7 @@ import re from re import Match, Pattern -from typing import Callable, Final, Union, cast +from typing import Callable, Final, cast from typing_extensions import TypeAlias as _TypeAlias import mypy.errorcodes as codes @@ -64,7 +64,7 @@ get_proper_types, ) -FormatStringExpr: _TypeAlias = Union[StrExpr, BytesExpr] +FormatStringExpr: _TypeAlias = StrExpr | BytesExpr Checkers: _TypeAlias = tuple[Callable[[Expression], None], Callable[[Type], bool]] MatchMap: _TypeAlias = dict[tuple[int, int], Match[str]] # span -> match diff --git a/mypy/config_parser.py b/mypy/config_parser.py index 2bfd2a1e2eef..af697821757f 100644 --- a/mypy/config_parser.py +++ b/mypy/config_parser.py @@ -14,15 +14,15 @@ import tomli as tomllib from collections.abc import Mapping, MutableMapping, Sequence -from typing import Any, Callable, Final, TextIO, Union +from typing import Any, Callable, Final, TextIO from typing_extensions import Never, 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] -] +_CONFIG_VALUE_TYPES: TypeAlias = ( + str | bool | int | float | dict[str, str] | list[str] | tuple[int, int] +) _INI_PARSER_CALLABLE: TypeAlias = Callable[[Any], _CONFIG_VALUE_TYPES] diff --git a/mypy/constant_fold.py b/mypy/constant_fold.py index 4582b2a7396d..e1b915df2298 100644 --- a/mypy/constant_fold.py +++ b/mypy/constant_fold.py @@ -5,7 +5,7 @@ from __future__ import annotations -from typing import Final, Union +from typing import Final from mypy.nodes import ( ComplexExpr, @@ -20,7 +20,7 @@ ) # All possible result types of constant folding -ConstantValue = Union[int, bool, float, complex, str] +ConstantValue = int | bool | float | complex | str CONST_TYPES: Final = (int, bool, float, complex, str) diff --git a/mypy/errors.py b/mypy/errors.py index 69e4fb4cf065..e7325cbe2265 100644 --- a/mypy/errors.py +++ b/mypy/errors.py @@ -6,7 +6,7 @@ from collections import defaultdict from collections.abc import Iterable, Iterator from itertools import chain -from typing import Callable, Final, NoReturn, Optional, TextIO, TypeVar +from typing import Callable, Final, NoReturn, TextIO, TypeVar from typing_extensions import Literal, Self, TypeAlias as _TypeAlias from mypy import errorcodes as codes @@ -155,7 +155,7 @@ def __init__( # Type used internally to represent errors: # (path, line, column, end_line, end_column, severity, message, code) -ErrorTuple: _TypeAlias = tuple[Optional[str], int, int, int, int, str, str, Optional[ErrorCode]] +ErrorTuple: _TypeAlias = tuple[str | None, int, int, int, int, str, str, ErrorCode | None] class ErrorWatcher: diff --git a/mypy/exportjson.py b/mypy/exportjson.py index dfc1cf5abbc6..3ee93ec0efcc 100644 --- a/mypy/exportjson.py +++ b/mypy/exportjson.py @@ -16,7 +16,7 @@ import argparse import json import sys -from typing import Any, Union +from typing import Any from typing_extensions import TypeAlias as _TypeAlias from librt.internal import ReadBuffer @@ -69,7 +69,7 @@ get_proper_type, ) -Json: _TypeAlias = Union[dict[str, Any], str] +Json: _TypeAlias = dict[str, Any] | str class Config: diff --git a/mypy/fastparse.py b/mypy/fastparse.py index 0e7b418d0375..19d7b5db21e2 100644 --- a/mypy/fastparse.py +++ b/mypy/fastparse.py @@ -4,7 +4,7 @@ import sys import warnings from collections.abc import Sequence -from typing import Any, Callable, Final, Literal, Optional, TypeVar, Union, cast, overload +from typing import Any, Callable, Final, Literal, TypeVar, Union, cast, overload from mypy import defaults, errorcodes as codes, message_registry from mypy.errors import Errors @@ -714,7 +714,7 @@ def fix_function_overloads(self, stmts: list[Statement]) -> list[Statement]: current_overload.extend(if_block_with_overload.body[-1].items) else: current_overload.append( - cast(Union[Decorator, FuncDef], if_block_with_overload.body[0]) + cast(Decorator | FuncDef, if_block_with_overload.body[0]) ) else: if last_if_stmt is not None: @@ -760,7 +760,7 @@ def fix_function_overloads(self, stmts: list[Statement]) -> list[Statement]: cast(list[IfStmt], if_block_with_overload.body[:-1]) ) last_if_overload = cast( - Union[Decorator, FuncDef, OverloadedFuncDef], + Decorator | FuncDef | OverloadedFuncDef, if_block_with_overload.body[-1], ) last_if_unknown_truth_value = if_unknown_truth_value @@ -806,9 +806,7 @@ def _check_ifstmt_for_overloads( ): return None - overload_name = cast( - Union[Decorator, FuncDef, OverloadedFuncDef], stmt.body[0].body[-1] - ).name + overload_name = cast(Decorator | FuncDef | OverloadedFuncDef, stmt.body[0].body[-1]).name if stmt.else_body is None: return overload_name @@ -991,7 +989,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[Type | None], translated_args) return_type = TypeConverter(self.errors, line=lineno).visit(func_type_ast.returns) # add implicit self type @@ -1646,7 +1644,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[str | None]", [None] * len(args)) + keyword_names, ) return self.set_line(e, n) diff --git a/mypy/literals.py b/mypy/literals.py index fd17e0471440..c53a93c26433 100644 --- a/mypy/literals.py +++ b/mypy/literals.py @@ -1,7 +1,7 @@ from __future__ import annotations from collections.abc import Iterable -from typing import Any, Final, Optional +from typing import Any, Final from typing_extensions import TypeAlias as _TypeAlias from mypy.nodes import ( @@ -164,7 +164,7 @@ def extract_var_from_literal_hash(key: Key) -> Var | None: return None -class _Hasher(ExpressionVisitor[Optional[Key]]): +class _Hasher(ExpressionVisitor[Key | None]): def visit_int_expr(self, e: IntExpr) -> Key: return ("Literal", e.value) diff --git a/mypy/modulefinder.py b/mypy/modulefinder.py index 5176b7e1df52..78d8329f1fae 100644 --- a/mypy/modulefinder.py +++ b/mypy/modulefinder.py @@ -13,7 +13,7 @@ import subprocess import sys from enum import Enum, unique -from typing import Final, Optional, Union +from typing import Final from typing_extensions import TypeAlias as _TypeAlias from pathspec import PathSpec @@ -60,7 +60,7 @@ def asdict(self) -> dict[str, tuple[str, ...]]: 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], tuple[int, int] | None]] PYTHON_EXTENSIONS: Final = [".pyi", ".py"] @@ -118,7 +118,7 @@ def error_message_templates(self, daemon: bool) -> tuple[str, list[str]]: # If we found the module, returns the path to the module as a str. # Otherwise, returns the reason why the module wasn't found. -ModuleSearchResult = Union[str, ModuleNotFoundReason] +ModuleSearchResult = str | ModuleNotFoundReason class BuildSource: diff --git a/mypy/plugins/singledispatch.py b/mypy/plugins/singledispatch.py index eb2bbe133bf0..a069fffbff20 100644 --- a/mypy/plugins/singledispatch.py +++ b/mypy/plugins/singledispatch.py @@ -1,7 +1,7 @@ from __future__ import annotations from collections.abc import Sequence -from typing import NamedTuple, TypeVar, Union +from typing import NamedTuple, TypeVar from typing_extensions import TypeAlias as _TypeAlias from mypy.messages import format_type @@ -67,7 +67,7 @@ def make_fake_register_class_instance( return Instance(info, type_args) -PluginContext: _TypeAlias = Union[FunctionContext, MethodContext] +PluginContext: _TypeAlias = FunctionContext | MethodContext def fail(ctx: PluginContext, msg: str, context: Context | None) -> None: diff --git a/mypy/scope.py b/mypy/scope.py index 766048c41180..bc8b7457c9a0 100644 --- a/mypy/scope.py +++ b/mypy/scope.py @@ -7,12 +7,11 @@ from collections.abc import Iterator from contextlib import contextmanager, nullcontext -from typing import Optional from typing_extensions import TypeAlias as _TypeAlias from mypy.nodes import FuncBase, TypeInfo -SavedScope: _TypeAlias = tuple[str, Optional[TypeInfo], Optional[FuncBase]] +SavedScope: _TypeAlias = tuple[str, TypeInfo | None, FuncBase | None] class Scope: diff --git a/mypy/semanal_main.py b/mypy/semanal_main.py index b2c43e6becb8..a9f492443f94 100644 --- a/mypy/semanal_main.py +++ b/mypy/semanal_main.py @@ -29,7 +29,7 @@ from collections.abc import Iterator from contextlib import nullcontext from itertools import groupby -from typing import TYPE_CHECKING, Callable, Final, Optional, Union +from typing import TYPE_CHECKING, Callable, Final from typing_extensions import TypeAlias as _TypeAlias import mypy.build @@ -358,12 +358,12 @@ def process_top_level_function( TargetInfo: _TypeAlias = tuple[ - str, Union[MypyFile, FuncDef, OverloadedFuncDef, Decorator], Optional[TypeInfo] + str, MypyFile | FuncDef | OverloadedFuncDef | Decorator, TypeInfo | None ] # Same as above but includes module as first item. FullTargetInfo: _TypeAlias = tuple[ - str, str, Union[MypyFile, FuncDef, OverloadedFuncDef, Decorator], Optional[TypeInfo] + str, str, MypyFile | FuncDef | OverloadedFuncDef | Decorator, TypeInfo | None ] diff --git a/mypy/server/astdiff.py b/mypy/server/astdiff.py index 15d472b64886..74a2e5023f33 100644 --- a/mypy/server/astdiff.py +++ b/mypy/server/astdiff.py @@ -114,7 +114,7 @@ class level -- these are handled at attribute level (say, 'mod.Cls.method' # For example, the snapshot of the 'int' type is ('Instance', 'builtins.int', ()). # Type snapshots are strict, they must be hashable and ordered (e.g. for Unions). -Primitive: _TypeAlias = Union[str, float, int, bool] # float is for Literal[3.14] support. +Primitive: _TypeAlias = str | float | int | bool # float is for Literal[3.14] support. SnapshotItem: _TypeAlias = tuple[Union[Primitive, "SnapshotItem"], ...] # Symbol snapshots can be more lenient. diff --git a/mypy/server/update.py b/mypy/server/update.py index 86ccb57c2a3f..16349a87546d 100644 --- a/mypy/server/update.py +++ b/mypy/server/update.py @@ -119,7 +119,7 @@ import sys import time from collections.abc import Sequence -from typing import Callable, Final, NamedTuple, Union +from typing import Callable, Final, NamedTuple from typing_extensions import TypeAlias as _TypeAlias from mypy.build import ( @@ -555,7 +555,7 @@ class BlockedUpdate(NamedTuple): messages: list[str] -UpdateResult: _TypeAlias = Union[NormalUpdate, BlockedUpdate] +UpdateResult: _TypeAlias = NormalUpdate | BlockedUpdate def update_module_isolated( diff --git a/mypy/stubtest.py b/mypy/stubtest.py index ada56a2489fe..570ae6e95d4d 100644 --- a/mypy/stubtest.py +++ b/mypy/stubtest.py @@ -59,7 +59,7 @@ def __repr__(self) -> str: MISSING: Final = Missing() T = TypeVar("T") -MaybeMissing: typing_extensions.TypeAlias = Union[T, Missing] +MaybeMissing: typing_extensions.TypeAlias = T | Missing class Unrepresentable: diff --git a/mypy/test/data.py b/mypy/test/data.py index 5b0ad84c0ba7..fc7be6ec2dd1 100644 --- a/mypy/test/data.py +++ b/mypy/test/data.py @@ -14,7 +14,7 @@ from dataclasses import dataclass from pathlib import Path from re import Pattern -from typing import Any, Final, NamedTuple, NoReturn, Union +from typing import Any, Final, NamedTuple, NoReturn from typing_extensions import TypeAlias as _TypeAlias import pytest @@ -43,7 +43,7 @@ class DeleteFile(NamedTuple): path: str -FileOperation: _TypeAlias = Union[UpdateFile, DeleteFile] +FileOperation: _TypeAlias = UpdateFile | DeleteFile def _file_arg_to_module(filename: str) -> str: diff --git a/mypy/treetransform.py b/mypy/treetransform.py index f5af5fb777b5..1a76a50a2d94 100644 --- a/mypy/treetransform.py +++ b/mypy/treetransform.py @@ -6,7 +6,7 @@ from __future__ import annotations from collections.abc import Iterable -from typing import Optional, cast +from typing import cast from mypy.nodes import ( GDEF, @@ -194,7 +194,7 @@ def visit_func_def(self, node: FuncDef) -> FuncDef: node.name, [self.copy_argument(arg) for arg in node.arguments], self.block(node.body), - cast(Optional[FunctionLike], self.optional_type(node.type)), + cast(FunctionLike | None, self.optional_type(node.type)), ) self.copy_function_attributes(new, node) @@ -224,7 +224,7 @@ def visit_lambda_expr(self, node: LambdaExpr) -> LambdaExpr: new = LambdaExpr( [self.copy_argument(arg) for arg in node.arguments], self.block(node.body), - cast(Optional[FunctionLike], self.optional_type(node.type)), + cast(FunctionLike | None, self.optional_type(node.type)), ) self.copy_function_attributes(new, node) return new @@ -528,7 +528,7 @@ def visit_op_expr(self, node: OpExpr) -> OpExpr: node.op, self.expr(node.left), self.expr(node.right), - cast(Optional[TypeAliasExpr], self.optional_expr(node.analyzed)), + cast(TypeAliasExpr | None, self.optional_expr(node.analyzed)), ) new.method_type = self.optional_type(node.method_type) return new diff --git a/mypy/types.py b/mypy/types.py index 09e4b74bb821..cdfc60a8e7df 100644 --- a/mypy/types.py +++ b/mypy/types.py @@ -5,7 +5,7 @@ import sys from abc import abstractmethod from collections.abc import Iterable, Sequence -from typing import TYPE_CHECKING, Any, ClassVar, Final, NewType, TypeVar, Union, cast, overload +from typing import TYPE_CHECKING, Any, ClassVar, Final, NewType, TypeVar, cast, overload from typing_extensions import Self, TypeAlias as _TypeAlias, TypeGuard from librt.internal import ( @@ -84,7 +84,7 @@ # # Note: Float values are only used internally. They are not accepted within # Literal[...]. -LiteralValue: _TypeAlias = Union[int, str, bool, float] +LiteralValue: _TypeAlias = int | str | bool | float # If we only import type_visitor in the middle of the file, mypy diff --git a/mypyc/build.py b/mypyc/build.py index c9ddaa7dab1f..e0aa91dc6afe 100644 --- a/mypyc/build.py +++ b/mypyc/build.py @@ -26,7 +26,7 @@ import sys import time from collections.abc import Iterable -from typing import TYPE_CHECKING, Any, NamedTuple, NoReturn, Union, cast +from typing import TYPE_CHECKING, Any, NamedTuple, NoReturn, cast import mypyc.build_setup # noqa: F401 from mypy.build import BuildSource @@ -119,7 +119,7 @@ class ModDesc(NamedTuple): from setuptools import Extension as _setuptools_Extension - Extension: TypeAlias = Union[_setuptools_Extension, _distutils_Extension] + Extension: TypeAlias = _setuptools_Extension | _distutils_Extension if sys.version_info >= (3, 12): # From setuptools' monkeypatch diff --git a/mypyc/codegen/emitmodule.py b/mypyc/codegen/emitmodule.py index 092b45c27e1c..959ad3a6d73d 100644 --- a/mypyc/codegen/emitmodule.py +++ b/mypyc/codegen/emitmodule.py @@ -9,7 +9,7 @@ import os import sys from collections.abc import Iterable -from typing import Optional, TypeVar +from typing import TypeVar from mypy.build import ( BuildResult, @@ -94,7 +94,7 @@ # its modules along with the name of the group. (Which can be None # only if we are compiling only a single group with a single file in it # and not using shared libraries). -Group = tuple[list[BuildSource], Optional[str]] +Group = tuple[list[BuildSource], str | None] Groups = list[Group] # A list of (file name, file contents) pairs. diff --git a/mypyc/codegen/literals.py b/mypyc/codegen/literals.py index 4cd41e0f4d32..4286bbea4840 100644 --- a/mypyc/codegen/literals.py +++ b/mypyc/codegen/literals.py @@ -1,13 +1,13 @@ from __future__ import annotations -from typing import Final, Union +from typing import Final from typing_extensions import TypeGuard # Supported Python literal types. All tuple / frozenset items must have supported # literal types as well, but we can't represent the type precisely. -LiteralValue = Union[ - str, bytes, int, bool, float, complex, tuple[object, ...], frozenset[object], None -] +LiteralValue = ( + str | bytes | int | bool | float | complex | tuple[object, ...] | frozenset[object] | None +) def _is_literal_value(obj: object) -> TypeGuard[LiteralValue]: diff --git a/mypyc/ir/ops.py b/mypyc/ir/ops.py index 072892f776df..beb709adfbd0 100644 --- a/mypyc/ir/ops.py +++ b/mypyc/ir/ops.py @@ -27,7 +27,7 @@ class to enable the new behavior. Sometimes adding a new abstract from abc import abstractmethod from collections.abc import Sequence -from typing import TYPE_CHECKING, Final, Generic, NamedTuple, TypeVar, Union, final +from typing import TYPE_CHECKING, Final, Generic, NamedTuple, TypeVar, final from mypy_extensions import trait @@ -1227,7 +1227,7 @@ def accept(self, visitor: OpVisitor[T]) -> T: # True steals all arguments, False steals none, a list steals those in matching positions -StealsDescription = Union[bool, list[bool]] +StealsDescription = bool | list[bool] @final diff --git a/mypyc/ir/pprint.py b/mypyc/ir/pprint.py index efefd76d15f0..e0a9e9d63208 100644 --- a/mypyc/ir/pprint.py +++ b/mypyc/ir/pprint.py @@ -4,7 +4,7 @@ from collections import defaultdict from collections.abc import Sequence -from typing import Any, Final, Union +from typing import Any, Final from mypyc.common import short_name from mypyc.ir.func_ir import FuncIR, all_values_full @@ -63,7 +63,7 @@ ) from mypyc.ir.rtypes import RType, is_bool_rprimitive, is_int_rprimitive -ErrorSource = Union[BasicBlock, Op] +ErrorSource = BasicBlock | Op class IRPrettyPrintVisitor(OpVisitor[str]): diff --git a/mypyc/irbuild/builder.py b/mypyc/irbuild/builder.py index 63930123135f..43e3d35d16b3 100644 --- a/mypyc/irbuild/builder.py +++ b/mypyc/irbuild/builder.py @@ -7,7 +7,7 @@ from collections.abc import Iterator, Sequence from contextlib import contextmanager -from typing import Any, Callable, Final, Union, overload +from typing import Any, Callable, Final, overload from mypy.build import Graph from mypy.maptype import map_instance_to_supertype @@ -146,7 +146,7 @@ class UnsupportedException(Exception): pass -SymbolTarget = Union[AssignmentTargetRegister, AssignmentTargetAttr] +SymbolTarget = AssignmentTargetRegister | AssignmentTargetAttr class IRBuilder: diff --git a/mypyc/irbuild/constant_fold.py b/mypyc/irbuild/constant_fold.py index b1133f95b18e..53274dd3f971 100644 --- a/mypyc/irbuild/constant_fold.py +++ b/mypyc/irbuild/constant_fold.py @@ -10,7 +10,7 @@ from __future__ import annotations -from typing import TYPE_CHECKING, Final, Union +from typing import TYPE_CHECKING, Final from mypy.constant_fold import constant_fold_binary_op, constant_fold_unary_op from mypy.nodes import ( @@ -32,7 +32,7 @@ from mypyc.irbuild.builder import IRBuilder # All possible result types of constant folding -ConstantValue = Union[int, float, complex, str, bytes] +ConstantValue = int | float | complex | str | bytes CONST_TYPES: Final = (int, float, complex, str, bytes) diff --git a/mypyc/irbuild/ll_builder.py b/mypyc/irbuild/ll_builder.py index 6baff44f2f82..bbc1d8e6b44a 100644 --- a/mypyc/irbuild/ll_builder.py +++ b/mypyc/irbuild/ll_builder.py @@ -8,7 +8,7 @@ import sys from collections.abc import Sequence -from typing import Callable, Final, Optional, cast +from typing import Callable, Final, cast from typing_extensions import TypeGuard from mypy.argmap import map_actuals_to_formals @@ -202,7 +202,7 @@ from mypyc.sametype import is_same_type from mypyc.subtype import is_subtype -DictEntry = tuple[Optional[Value], Value] +DictEntry = tuple[Value | None, Value] # If the number of items is less than the threshold when initializing # a list, we would inline the generate IR using SetMem and expanded diff --git a/mypyc/irbuild/specialize.py b/mypyc/irbuild/specialize.py index b64f51043b13..ad2a591a0e7d 100644 --- a/mypyc/irbuild/specialize.py +++ b/mypyc/irbuild/specialize.py @@ -14,7 +14,7 @@ from __future__ import annotations -from typing import Callable, Final, Optional, cast +from typing import Callable, Final, cast from mypy.nodes import ( ARG_NAMED, @@ -122,7 +122,7 @@ # # Specializers take three arguments: the IRBuilder, the CallExpr being # compiled, and the RefExpr that is the left hand side of the call. -Specializer = Callable[["IRBuilder", CallExpr, RefExpr], Optional[Value]] +Specializer = Callable[["IRBuilder", CallExpr, RefExpr], Value | None] # Dictionary containing all configured specializers. # diff --git a/mypyc/lower/registry.py b/mypyc/lower/registry.py index a20990fe39ae..da1e7fd9537a 100644 --- a/mypyc/lower/registry.py +++ b/mypyc/lower/registry.py @@ -1,12 +1,12 @@ from __future__ import annotations -from typing import Callable, Final, Optional, TypeVar +from typing import Callable, Final, TypeVar from mypyc.ir.ops import Value from mypyc.irbuild.ll_builder import LowLevelIRBuilder LowerFunc = Callable[[LowLevelIRBuilder, list[Value], int], Value] -LowerFuncOpt = Callable[[LowLevelIRBuilder, list[Value], int], Optional[Value]] +LowerFuncOpt = Callable[[LowLevelIRBuilder, list[Value], int], Value | None] lowering_registry: Final[dict[str, LowerFuncOpt]] = {} diff --git a/mypyc/transform/ir_transform.py b/mypyc/transform/ir_transform.py index bcb6db9b0daf..4724e9d96fe8 100644 --- a/mypyc/transform/ir_transform.py +++ b/mypyc/transform/ir_transform.py @@ -2,7 +2,7 @@ from __future__ import annotations -from typing import Final, Optional +from typing import Final from mypyc.ir.ops import ( Assign, @@ -52,7 +52,7 @@ from mypyc.irbuild.ll_builder import LowLevelIRBuilder -class IRTransform(OpVisitor[Optional[Value]]): +class IRTransform(OpVisitor[Value | None]): """Identity transform. Subclass and override to perform changes to IR.