diff --git a/docs/source/cheat_sheet.rst b/docs/source/cheat_sheet.rst index eb71bcde6ba4..08b051f90918 100644 --- a/docs/source/cheat_sheet.rst +++ b/docs/source/cheat_sheet.rst @@ -19,8 +19,7 @@ Built-in types .. code-block:: python - from typing import List, Set, Dict, Tuple, Optional - import six + from typing import List, Set, Dict, Tuple, Text, Optional # For simple built-in types, just use the name of the type. x = 1 # type: int @@ -39,9 +38,9 @@ Built-in types # For tuples, we specify the types of all the elements. x = (3, "yes", 7.5) # type: Tuple[int, str, float] - # For textual data, we generally use six.text_type. + # For textual data, use Text. # This is `unicode` in Python 2 and `str` in Python 3. - x = ["string", u"unicode"] # type: List[six.text_type] + x = ["string", u"unicode"] # type: List[Text] # Use Optional for values that could be None. input_str = f() # type: Optional[str] @@ -177,11 +176,17 @@ Other stuff .. code-block:: python # typing.Match describes regex matches from the re module. - from typing import Match + from typing import Match, AnyStr x = re.match(r'[0-9]+', "15") # type: Match[str] + # Use AnyStr for functions that should accept any kind of string + # without allowing different kinds of strings to mix. + def concat(a: AnyStr, b: AnyStr) -> AnyStr: + return a + b + concat(u"foo", u"bar") # type: unicode + concat(b"foo", b"bar") # type: bytes + # TODO: add typing.IO: e.g., sys.stdout has type IO[str] # TODO: add TypeVar and a simple generic function - # TODO: add AnyStr (and mention up next to strings) diff --git a/docs/source/duck_type_compatibility.rst b/docs/source/duck_type_compatibility.rst index 8b20a8ea8278..a128b691dd3e 100644 --- a/docs/source/duck_type_compatibility.rst +++ b/docs/source/duck_type_compatibility.rst @@ -35,3 +35,6 @@ and also behaves as expected: silently pass type checking. In Python 3 ``str`` and ``bytes`` are separate, unrelated types and this kind of error is easy to detect. This a good reason for preferring Python 3 over Python 2! + + See :ref:`text-and-anystr` for details on how to enforce that a + value must be a unicode string in a cross-compatible way. diff --git a/docs/source/kinds_of_types.rst b/docs/source/kinds_of_types.rst index 16c17e1d888d..659475839459 100644 --- a/docs/source/kinds_of_types.rst +++ b/docs/source/kinds_of_types.rst @@ -657,3 +657,47 @@ Now mypy will infer the correct type of the result when we call For more details about ``Type[]`` see `PEP 484 `_. + +.. _text-and-anystr: + +Text and AnyStr +*************** + +Sometimes you may want to write a function which will accept only unicode +strings. This can be challenging to do in a codebase intended to run in +both Python 2 and Python 3 since ``str`` means something different in both +versions and ``unicode`` is not a keyword in Python 3. + +To help solve this issue, use ``typing.Text`` which is aliased to +``unicode`` in Python 2 and to ``str`` in Python 3. This allows you to +indicate that a function should accept only unicode strings in a +cross-compatible way: + +.. code-block:: python + + from typing import Text + + def unicode_only(s: Text) -> Text: + return s + u'\u2713' + +In other cases, you may want to write a function that will work with any +kind of string but will not let you mix two different string types. To do +so use ``typing.AnyStr``: + +.. code-block:: python + + from typing import AnyStr + + def concat(x: AnyStr, y: AnyStr) -> AnyStr: + return x + y + + concat('a', 'b') # Okay + concat(b'a', b'b') # Okay + concat('a', b'b') # Error: cannot mix bytes and unicode + +For more details, see :ref:`type-variable-value-restriction`. + +.. note:: + + How ``bytes``, ``str``, and ``unicode`` are handled between Python 2 and + Python 3 may change in future versions of mypy. diff --git a/mypy/build.py b/mypy/build.py index 8ca0e5f4db4f..848d746f07da 100644 --- a/mypy/build.py +++ b/mypy/build.py @@ -1181,7 +1181,7 @@ def wrap_context(self) -> Iterator[None]: except CompileError: raise except Exception as err: - report_internal_error(err, self.path, 0) + report_internal_error(err, self.path, 0, self.manager.errors) self.manager.errors.set_import_context(save_import_context) self.check_blockers() @@ -1344,6 +1344,7 @@ def load_graph(sources: List[BuildSource], manager: BuildManager) -> Graph: # TODO: Consider whether to go depth-first instead. This may # affect the order in which we process files within import cycles. new = collections.deque() # type: collections.deque[State] + entry_points = set() # type: Set[str] # Seed the graph with the initial root sources. for bs in sources: try: @@ -1356,11 +1357,16 @@ def load_graph(sources: List[BuildSource], manager: BuildManager) -> Graph: manager.errors.raise_error() graph[st.id] = st new.append(st) + entry_points.add(bs.module) # Collect dependencies. We go breadth-first. while new: st = new.popleft() - for dep in st.ancestors + st.dependencies: - if dep not in graph: + for dep in st.ancestors + st.dependencies + st.suppressed: + # We don't want to recheck imports marked with '# type: ignore' + # so we ignore any suppressed module not explicitly re-included + # from the command line. + ignored = dep in st.suppressed and dep not in entry_points + if dep not in graph and not ignored: try: if dep in st.ancestors: # TODO: Why not 'if dep not in st.dependencies' ? @@ -1380,6 +1386,11 @@ def load_graph(sources: List[BuildSource], manager: BuildManager) -> Graph: new.append(newst) if dep in st.ancestors and dep in graph: graph[dep].child_modules.add(st.id) + if dep in graph and dep in st.suppressed: + # Previously suppressed file is now visible + if dep in st.suppressed: + st.suppressed.remove(dep) + st.dependencies.append(dep) for id, g in graph.items(): if g.has_new_submodules(): g.parse_file() diff --git a/mypy/checker.py b/mypy/checker.py index 881f02b670ce..8614148c7298 100644 --- a/mypy/checker.py +++ b/mypy/checker.py @@ -201,7 +201,7 @@ def accept(self, node: Node, type_context: Type = None) -> Type: try: typ = node.accept(self) except Exception as err: - report_internal_error(err, self.errors.file, node.line) + report_internal_error(err, self.errors.file, node.line, self.errors) self.type_context.pop() self.store_type(node, typ) if self.typing_mode_none(): @@ -809,9 +809,13 @@ def check_method_override_for_base_with_name( # Map the overridden method type to subtype context so that # it can be checked for compatibility. original_type = base_attr.type - if original_type is None and isinstance(base_attr.node, - FuncDef): - original_type = self.function_type(base_attr.node) + if original_type is None: + if isinstance(base_attr.node, FuncDef): + original_type = self.function_type(base_attr.node) + elif isinstance(base_attr.node, Decorator): + original_type = self.function_type(base_attr.node.func) + else: + assert False, str(base_attr.node) if isinstance(original_type, FunctionLike): original = map_type_from_supertype( method_type(original_type), @@ -825,7 +829,6 @@ def check_method_override_for_base_with_name( base.name(), defn) else: - assert original_type is not None self.msg.signature_incompatible_with_supertype( defn.name(), name, base.name(), defn) @@ -2248,7 +2251,8 @@ def leave_partial_types(self) -> None: partial_types = self.partial_types.pop() if not self.current_node_deferred: for var, context in partial_types.items(): - if experiments.STRICT_OPTIONAL and cast(PartialType, var.type).type is None: + if (experiments.STRICT_OPTIONAL and + isinstance(var.type, PartialType) and var.type.type is None): # None partial type: assume variable is intended to have type None var.type = NoneTyp() else: diff --git a/mypy/checkexpr.py b/mypy/checkexpr.py index 4fc9ac6e9cca..c34e7550b15a 100644 --- a/mypy/checkexpr.py +++ b/mypy/checkexpr.py @@ -158,8 +158,10 @@ def try_infer_partial_type(self, e: CallExpr) -> None: var = cast(Var, e.callee.expr.node) partial_types = self.chk.find_partial_types(var) if partial_types is not None and not self.chk.current_node_deferred: - partial_type = cast(PartialType, var.type) - if partial_type is None or partial_type.type is None: + partial_type = var.type + if (partial_type is None or + not isinstance(partial_type, PartialType) or + partial_type.type is None): # A partial None type -> can't infer anything. return typename = partial_type.type.fullname() @@ -1538,55 +1540,68 @@ def check_generator_or_comprehension(self, gen: GeneratorExpr, type_name: str, id_for_messages: str) -> Type: """Type check a generator expression or a list comprehension.""" - self.check_for_comp(gen) + with self.chk.binder.frame_context(): + self.check_for_comp(gen) - # Infer the type of the list comprehension by using a synthetic generic - # callable type. - tvdef = TypeVarDef('T', -1, [], self.chk.object_type()) - tv = TypeVarType(tvdef) - constructor = CallableType( - [tv], - [nodes.ARG_POS], - [None], - self.chk.named_generic_type(type_name, [tv]), - self.chk.named_type('builtins.function'), - name=id_for_messages, - variables=[tvdef]) - return self.check_call(constructor, - [gen.left_expr], [nodes.ARG_POS], gen)[0] + # Infer the type of the list comprehension by using a synthetic generic + # callable type. + tvdef = TypeVarDef('T', -1, [], self.chk.object_type()) + tv = TypeVarType(tvdef) + constructor = CallableType( + [tv], + [nodes.ARG_POS], + [None], + self.chk.named_generic_type(type_name, [tv]), + self.chk.named_type('builtins.function'), + name=id_for_messages, + variables=[tvdef]) + return self.check_call(constructor, + [gen.left_expr], [nodes.ARG_POS], gen)[0] def visit_dictionary_comprehension(self, e: DictionaryComprehension) -> Type: """Type check a dictionary comprehension.""" - self.check_for_comp(e) - - # Infer the type of the list comprehension by using a synthetic generic - # callable type. - ktdef = TypeVarDef('KT', -1, [], self.chk.object_type()) - vtdef = TypeVarDef('VT', -2, [], self.chk.object_type()) - kt = TypeVarType(ktdef) - vt = TypeVarType(vtdef) - constructor = CallableType( - [kt, vt], - [nodes.ARG_POS, nodes.ARG_POS], - [None, None], - self.chk.named_generic_type('builtins.dict', [kt, vt]), - self.chk.named_type('builtins.function'), - name='', - variables=[ktdef, vtdef]) - return self.check_call(constructor, - [e.key, e.value], [nodes.ARG_POS, nodes.ARG_POS], e)[0] + with self.chk.binder.frame_context(): + self.check_for_comp(e) + + # Infer the type of the list comprehension by using a synthetic generic + # callable type. + ktdef = TypeVarDef('KT', -1, [], self.chk.object_type()) + vtdef = TypeVarDef('VT', -2, [], self.chk.object_type()) + kt = TypeVarType(ktdef) + vt = TypeVarType(vtdef) + constructor = CallableType( + [kt, vt], + [nodes.ARG_POS, nodes.ARG_POS], + [None, None], + self.chk.named_generic_type('builtins.dict', [kt, vt]), + self.chk.named_type('builtins.function'), + name='', + variables=[ktdef, vtdef]) + return self.check_call(constructor, + [e.key, e.value], [nodes.ARG_POS, nodes.ARG_POS], e)[0] def check_for_comp(self, e: Union[GeneratorExpr, DictionaryComprehension]) -> None: """Check the for_comp part of comprehensions. That is the part from 'for': ... for x in y if z + + Note: This adds the type information derived from the condlists to the current binder. """ - with self.chk.binder.frame_context(): - for index, sequence, conditions in zip(e.indices, e.sequences, - e.condlists): - sequence_type = self.chk.analyze_iterable_item_type(sequence) - self.chk.analyze_index_variables(index, sequence_type, e) - for condition in conditions: - self.accept(condition) + for index, sequence, conditions in zip(e.indices, e.sequences, + e.condlists): + sequence_type = self.chk.analyze_iterable_item_type(sequence) + self.chk.analyze_index_variables(index, sequence_type, e) + for condition in conditions: + self.accept(condition) + + # values are only part of the comprehension when all conditions are true + true_map, _ = mypy.checker.find_isinstance_check( + condition, self.chk.type_map, + self.chk.typing_mode_weak() + ) + + if true_map: + for var, type in true_map.items(): + self.chk.binder.push(var, type) def visit_conditional_expr(self, e: ConditionalExpr) -> Type: cond_type = self.accept(e.cond) diff --git a/mypy/docstring.py b/mypy/docstring.py deleted file mode 100644 index d78a81d161af..000000000000 --- a/mypy/docstring.py +++ /dev/null @@ -1,204 +0,0 @@ -"""Find type annotations from a docstring. - -Do not actually try to parse the annotations, just return them as strings. - -Also recognize some common non-PEP-484 aliases such as 'a string' for 'str' -and 'list of int' for 'List[int]'. - -Based on original implementation by Kyle Consalus. - -TODO: Decide whether it makes sense to do the heuristic analysis of aliases and natural - language type descriptions as it's all kind of ad hoc. -""" - -import re -from typing import Optional, List, Tuple, Dict, Sequence -from collections import OrderedDict - - -_example1 = """Fetches rows from a Bigtable. - - Retrieves rows pertaining to the given keys from the Table instance - represented by big_table. Silly things may happen if - other_silly_variable is not None. - - Args: - big_table: An open Bigtable Table instance. - keys (Sequence[str]): A sequence of strings representing the key of each table row - to fetch. - but: if the keys are broken, we die. - other_silly_variable (int): Another optional variable, that has a much - longer name than the other args, and which does nothing. - abc0 (Tuple[int, bool]): Hi. - abc (Tuple[int, bool], optional): Hi. - - Returns: - Dict[str, int]: Things. - - Raises: - IOError: An error occurred accessing the bigtable.Table object. - """ - - -# Regular expression that finds the argument name and type in a line such -# as ' name (type): description'. -PARAM_RE = re.compile(r'^\s*(?P[A-Za-z_][A-Za-z_0-9]*)(\s+\((?P[^)]+)\))?:') - -# Type strings with these brackets are rejected. -BRACKET_RE = re.compile(r'\(|\)|\{|\}') - -# Support some commonly used type aliases that aren't normally valid in annotations. -# TODO: Optionally reject these (or give a warning if these are used). -translations = { - 'obj': 'Any', - 'boolean': 'bool', - 'string': 'str', - 'integer': 'int', - 'number': 'float', - 'list': 'List[Any]', - 'set': 'Set[Any]', - 'sequence': 'Sequence[Any]', - 'iterable': 'Iterable[Any]', - 'dict': 'Dict[Any, Any]', - 'dictionary': 'Dict[Any, Any]', - 'mapping': 'Mapping[Any, Any]', -} - -# Some common types that we should recognize. -known_types = [ - 'int', 'str', 'unicode', 'bool', 'float', 'None', 'tuple', -] - -known_generic_types = [ - 'List', 'Set', 'Dict', 'Iterable', 'Sequence', 'Mapping', -] - -# Some natural language patterns that we want to support in docstrings. -known_patterns = [ - ('list of ?', 'List[?]'), - ('set of ?', 'List[?]'), - ('sequence of ?', 'Sequence[?]'), - ('optional ?', 'Optional[?]'), -] - - -class DocstringTypes(object): - def __init__(self) -> None: - self.args = OrderedDict() # type: Dict[str, Optional[str]] - self.rettype = None # type: Optional[str] - - def as_type_str(self) -> str: - return ('(' + ','.join([v or 'Any' for v in self.args.values()]) + - ') -> ' + (self.rettype or 'Any')) - - def __str__(self) -> str: - return repr({'args': self.args, 'return': self.rettype}) - - -def wsprefix(s: str) -> str: - return s[:len(s) - len(s.lstrip())] - - -def scrubtype(typestr: Optional[str], only_known: bool =False) -> Optional[str]: - if typestr is None: - return typestr - - # Reject typestrs with parentheses or curly braces. - if BRACKET_RE.search(typestr): - return None - - # Reject typestrs whose square brackets don't match & those with commas outside square - # brackets. - bracket_level = 0 - for c in typestr: - if c == '[': - bracket_level += 1 - elif c == ']': - bracket_level -= 1 - if bracket_level < 0: # Square brackets don't match - return None - elif c == ',' and bracket_level == 0: # A comma appears outside brackets - return None - if bracket_level > 0: - return None - - recognized = False - typestr = typestr.strip() - for prefix in ('a', 'A', 'an', 'An', 'the', 'The'): - if typestr.startswith(prefix + ' '): - typestr = typestr[len(prefix) + 1:] - if typestr in translations: - typestr = translations[typestr] - recognized = True - if typestr in known_types: - recognized = True - if any(typestr.startswith(t + '[') for t in known_generic_types): - recognized = True - for pattern, repl in known_patterns: - pattern = pattern.replace('?', '([a-zA-Z]+)') + '$' - m = re.match(pattern, typestr) - if m: - arg = scrubtype(m.group(1), only_known=only_known) - if arg: - typestr = repl.replace('?', arg) - recognized = True - if not recognized and only_known: - # This is potentially a type but not one of the known types. - return None - return typestr - - -def parse_args(lines: List[str]) -> Tuple[Dict[str, str], List[str]]: - res = OrderedDict() # type: Dict[str, str] - indent = wsprefix(lines[0]) - while lines: - l = lines[0] - if l.strip() in ('Returns:', 'Raises:'): - break - lines = lines[1:] - if not l or l.isspace(): - break - if not wsprefix(l) == indent: - continue - m = PARAM_RE.match(l) - if m: - gd = m.groupdict() - res[gd['name']] = scrubtype(gd['type']) - return res, lines - - -def parse_return(lines: List[str]) -> Tuple[Optional[str], List[str]]: - res = None # type: Optional[str] - while lines and lines[0].strip == '': - lines = lines[1:] - if lines: - l = lines[0] - lines = lines[1:] - segs = l.strip().split(':', 1) - if len(segs) >= 1: - res = scrubtype(segs[0], only_known=(len(segs) == 1)) - return res, lines - - -def parse_docstring(pds: str) -> DocstringTypes: - ds = DocstringTypes() - lines = pds.splitlines() - while lines: - first = lines[0] - if first.strip() in ('Args:', 'Params:', 'Arguments:'): - ds.args, lines = parse_args(lines[1:]) - break - lines = lines[1:] - while lines: - first = lines[0] - if first.strip() == 'Returns:': - ds.rettype, lines = parse_return(lines[1:]) - break - lines = lines[1:] - if not ds.args: - return None - return ds - - -if __name__ == '__main__': - print(parse_docstring(_example1)) diff --git a/mypy/errors.py b/mypy/errors.py index de5f735678fa..f9da1db9e947 100644 --- a/mypy/errors.py +++ b/mypy/errors.py @@ -409,31 +409,64 @@ def remove_path_prefix(path: str, prefix: str) -> str: # Corresponds to command-line flag --pdb. drop_into_pdb = False +# Corresponds to command-line flag --show-traceback. +show_tb = False + def set_drop_into_pdb(flag: bool) -> None: global drop_into_pdb drop_into_pdb = flag -def report_internal_error(err: Exception, file: str, line: int) -> None: - """Display stack trace and file location for an internal error + exit.""" - if drop_into_pdb: - import pdb - pdb.post_mortem(sys.exc_info()[2]) - tb = traceback.extract_stack()[:-2] - tb2 = traceback.extract_tb(sys.exc_info()[2]) - print('Traceback (most recent call last):') - for s in traceback.format_list(tb + tb2): - print(s.rstrip('\n')) - print('{}: {}'.format(type(err).__name__, err)) - print('\n*** INTERNAL ERROR ***', file=sys.stderr) +def set_show_tb(flag: bool) -> None: + global show_tb + show_tb = flag + + +def report_internal_error(err: Exception, file: str, line: int, errors: Errors) -> None: + """Report internal error and exit. + + This optionally starts pdb or shows a traceback. + """ + # Dump out errors so far, they often provide a clue. + # But catch unexpected errors rendering them. + try: + for msg in errors.messages(): + print(msg) + except Exception as e: + print("Failed to dump errors:", repr(e), file=sys.stderr) + + # Compute file:line prefix for official-looking error messages. if line: prefix = '{}:{}'.format(file, line) else: prefix = file - print('\n{}: error: Internal error --'.format(prefix), + + # Print "INTERNAL ERROR" message. + print('{}: error: INTERNAL ERROR --'.format(prefix), 'please report a bug at https://github.com/python/mypy/issues', file=sys.stderr) - print('\nNOTE: you can use "mypy --pdb ..." to drop into the debugger when this happens.', - file=sys.stderr) - sys.exit(1) + + # If requested, drop into pdb. This overrides show_tb. + if drop_into_pdb: + print('Dropping into pdb', file=sys.stderr) + import pdb + pdb.post_mortem(sys.exc_info()[2]) + + # If requested, print traceback, else print note explaining how to get one. + if not show_tb: + if not drop_into_pdb: + print('{}: note: please use --show-traceback to print a traceback ' + 'when reporting a bug'.format(prefix), + file=sys.stderr) + else: + tb = traceback.extract_stack()[:-2] + tb2 = traceback.extract_tb(sys.exc_info()[2]) + print('Traceback (most recent call last):') + for s in traceback.format_list(tb + tb2): + print(s.rstrip('\n')) + print('{}: {}'.format(type(err).__name__, err)) + print('{}: note: use --pdb to drop into pdb'.format(prefix), file=sys.stderr) + + # Exit. The caller has nothing more to say. + raise SystemExit(1) diff --git a/mypy/fastparse.py b/mypy/fastparse.py index 1db7004f6713..24323174bdb4 100644 --- a/mypy/fastparse.py +++ b/mypy/fastparse.py @@ -284,6 +284,9 @@ def do_func_def(self, n: Union[ast35.FunctionDef, ast35.AsyncFunctionDef], arg_types = [a.type_annotation for a in args] return_type = TypeConverter(line=n.lineno).visit(n.returns) + for arg, arg_type in zip(args, arg_types): + self.set_type_optional(arg_type, arg.initializer) + if isinstance(return_type, UnboundType): return_type.is_ret_type = True @@ -329,9 +332,7 @@ def set_type_optional(self, type: Type, initializer: Node) -> None: def transform_args(self, args: ast35.arguments, line: int) -> List[Argument]: def make_argument(arg: ast35.arg, default: Optional[ast35.expr], kind: int) -> Argument: arg_type = TypeConverter(line=line).visit(arg.annotation) - converted_default = self.visit(default) - self.set_type_optional(arg_type, converted_default) - return Argument(Var(arg.arg), arg_type, converted_default, kind) + return Argument(Var(arg.arg), arg_type, self.visit(default), kind) new_args = [] num_no_defaults = len(args.args) - len(args.defaults) diff --git a/mypy/join.py b/mypy/join.py index e695257a6033..006cc6d5eb4a 100644 --- a/mypy/join.py +++ b/mypy/join.py @@ -71,6 +71,9 @@ def join_types(s: Type, t: Type) -> Type: if isinstance(s, ErasedType): return t + if isinstance(s, UnionType) and not isinstance(t, UnionType): + s, t = t, s + if isinstance(s, NoneTyp) and not isinstance(t, NoneTyp): s, t = t, s @@ -119,8 +122,12 @@ def visit_none_type(self, t: NoneTyp) -> Type: if experiments.STRICT_OPTIONAL: if isinstance(self.s, (NoneTyp, UninhabitedType)): return t + elif isinstance(self.s, UnboundType): + return AnyType() + elif isinstance(self.s, Void) or isinstance(self.s, ErrorType): + return ErrorType() else: - return self.default(self.s) + return UnionType.make_simplified_union([self.s, t]) else: if not isinstance(self.s, Void): return self.s diff --git a/mypy/main.py b/mypy/main.py index 01f57089807b..6869896d7c79 100644 --- a/mypy/main.py +++ b/mypy/main.py @@ -12,7 +12,7 @@ from mypy import git from mypy import experiments from mypy.build import BuildSource, BuildResult, PYTHON_EXTENSIONS -from mypy.errors import CompileError, set_drop_into_pdb +from mypy.errors import CompileError, set_drop_into_pdb, set_show_tb from mypy.options import Options, BuildType from mypy.version import __version__ @@ -33,6 +33,8 @@ def main(script_path: str) -> None: sources, options = process_options(sys.argv[1:]) if options.pdb: set_drop_into_pdb(True) + if options.show_traceback: + set_show_tb(True) f = sys.stdout try: res = type_check_only(sources, bin_dir, options) @@ -137,7 +139,7 @@ def parse_version(v: str) -> Tuple[int, int]: version='%(prog)s ' + __version__) parser.add_argument('--python-version', type=parse_version, metavar='x.y', help='use Python x.y') - parser.add_argument('--py2', dest='python_version', action='store_const', + parser.add_argument('-2', '--py2', dest='python_version', action='store_const', const=defaults.PYTHON2_VERSION, help="use Python 2 mode") parser.add_argument('-s', '--silent-imports', action='store_true', help="don't follow imports to .py files") @@ -172,6 +174,8 @@ def parse_version(v: str) -> Tuple[int, int]: dest='special-opts:strict_optional', help="enable experimental strict Optional checks") parser.add_argument('--pdb', action='store_true', help="invoke pdb on fatal error") + parser.add_argument('--show-traceback', '--tb', action='store_true', + help="show traceback on fatal error") parser.add_argument('--stats', action='store_true', dest='dump_type_stats', help="dump stats") parser.add_argument('--inferstats', action='store_true', dest='dump_inference_stats', help="dump type inference stats") diff --git a/mypy/nodes.py b/mypy/nodes.py index bc25b8441045..07c9282a09c8 100644 --- a/mypy/nodes.py +++ b/mypy/nodes.py @@ -1504,7 +1504,7 @@ class GeneratorExpr(Expression): """Generator expression ... for ... in ... [ for ... in ... ] [ if ... ].""" left_expr = None # type: Expression - sequences_expr = None # type: List[Expression] + sequences = None # type: List[Expression] condlists = None # type: List[List[Expression]] indices = None # type: List[Expression] @@ -1548,7 +1548,7 @@ class DictionaryComprehension(Expression): key = None # type: Expression value = None # type: Expression - sequences_expr = None # type: List[Expression] + sequences = None # type: List[Expression] condlists = None # type: List[List[Expression]] indices = None # type: List[Expression] diff --git a/mypy/options.py b/mypy/options.py index 84675efd3f8d..bfb174822f62 100644 --- a/mypy/options.py +++ b/mypy/options.py @@ -41,6 +41,7 @@ def __init__(self) -> None: # -- development options -- self.verbosity = 0 # More verbose messages (for troubleshooting) self.pdb = False + self.show_traceback = False self.dump_type_stats = False self.dump_inference_stats = False diff --git a/mypy/parse.py b/mypy/parse.py index d76ca55c75a3..94d7b7d0a62c 100644 --- a/mypy/parse.py +++ b/mypy/parse.py @@ -8,7 +8,7 @@ from typing import List, Tuple, Any, Set, cast, Union, Optional -from mypy import lex, docstring +from mypy import lex from mypy.lex import ( Token, Eof, Bom, Break, Name, Colon, Dedent, IntLit, StrLit, BytesLit, UnicodeLit, FloatLit, Op, Indent, Keyword, Punct, LexError, ComplexLit, @@ -479,6 +479,10 @@ def parse_function(self, no_type_checks: bool=False) -> FuncDef: if is_error: return None + if typ: + for arg, arg_type in zip(args, typ.arg_types): + self.set_type_optional(arg_type, arg.initializer) + if typ and isinstance(typ.ret_type, UnboundType): typ.ret_type.is_ret_type = True @@ -782,8 +786,6 @@ def parse_normal_arg(self, require_named: bool, else: kind = nodes.ARG_POS - self.set_type_optional(type, initializer) - return Argument(variable, type, initializer, kind), require_named def set_type_optional(self, type: Type, initializer: Node) -> None: @@ -859,17 +861,6 @@ def parse_block(self, allow_type: bool = False) -> Tuple[Block, Type]: type = self.parse_type_comment(brk, signature=True) self.expect_indent() stmt_list = [] # type: List[Node] - if allow_type: - cur = self.current() - if type is None and isinstance(cur, StrLit): - ds = docstring.parse_docstring(cur.parsed()) - if ds and False: # TODO: Enable when this is working. - try: - type = parse_str_as_signature(ds.as_type_str(), cur.line) - except TypeParseError: - # We don't require docstrings to be actually correct. - # TODO: Report something here. - type = None while (not isinstance(self.current(), Dedent) and not isinstance(self.current(), Eof)): try: diff --git a/mypy/semanal.py b/mypy/semanal.py index fa5bced17dbd..ae7841d95c30 100644 --- a/mypy/semanal.py +++ b/mypy/semanal.py @@ -2247,7 +2247,7 @@ def lookup(self, name: str, ctx: Context) -> SymbolTableNode: return None # 2. Class attributes (if within class definition) if self.is_class_scope() and name in self.type.names: - return self.type[name] + return self.type.names[name] # 3. Local (function) scopes for table in reversed(self.locals): if table is not None and name in table: @@ -2461,7 +2461,7 @@ def accept(self, node: Node) -> None: try: node.accept(self) except Exception as err: - report_internal_error(err, self.errors.file, node.line) + report_internal_error(err, self.errors.file, node.line, self.errors) class FirstPass(NodeVisitor): @@ -2673,7 +2673,7 @@ def accept(self, node: Node) -> None: try: node.accept(self) except Exception as err: - report_internal_error(err, self.errors.file, node.line) + report_internal_error(err, self.errors.file, node.line, self.errors) def visit_block(self, b: Block) -> None: if b.is_unreachable: diff --git a/mypy/stats.py b/mypy/stats.py index 952dcd5cff1d..ac914f4e0e8a 100644 --- a/mypy/stats.py +++ b/mypy/stats.py @@ -222,7 +222,7 @@ def dump_type_stats(tree: Node, path: str, inferred: bool = False, def is_special_module(path: str) -> bool: - return os.path.basename(path) in ('abc.py', 'typing.py', 'builtins.py') + return os.path.basename(path) in ('abc.pyi', 'typing.pyi', 'builtins.pyi') def is_imprecise(t: Type) -> bool: diff --git a/mypy/test/data.py b/mypy/test/data.py index 22d842688d40..548872f201ee 100644 --- a/mypy/test/data.py +++ b/mypy/test/data.py @@ -57,10 +57,10 @@ def parse_test_cases( mpath = os.path.join(os.path.dirname(path), p[i].arg) f = open(mpath) if p[i].id == 'builtins': - fnam = 'builtins.py' + fnam = 'builtins.pyi' else: # Python 2 - fnam = '__builtin__.py' + fnam = '__builtin__.pyi' files.append((os.path.join(base_path, fnam), f.read())) f.close() elif p[i].id == 'stale': diff --git a/mypy/test/testcheck.py b/mypy/test/testcheck.py index acec6e3eda37..7f9c345c85aa 100644 --- a/mypy/test/testcheck.py +++ b/mypy/test/testcheck.py @@ -17,7 +17,7 @@ assert_string_arrays_equal, normalize_error_messages, testcase_pyversion, update_testcase_output, ) -from mypy.errors import CompileError +from mypy.errors import CompileError, set_show_tb from mypy.options import Options from mypy import experiments @@ -88,7 +88,6 @@ def run_case(self, testcase: DataDrivenTestCase) -> None: # We briefly sleep to make sure file timestamps are distinct. self.clear_cache() self.run_case_once(testcase, 1) - time.sleep(0.1) self.run_case_once(testcase, 2) elif optional: try: @@ -107,12 +106,13 @@ def clear_cache(self) -> None: def run_case_once(self, testcase: DataDrivenTestCase, incremental=0) -> None: find_module_clear_caches() - program_text = '\n'.join(testcase.input) - module_name, program_name, program_text = self.parse_module(program_text) + original_program_text = '\n'.join(testcase.input) + module_data = self.parse_module(original_program_text, incremental) - options = self.parse_options(program_text) + options = self.parse_options(original_program_text) options.use_builtins_fixtures = True options.python_version = testcase_pyversion(testcase.file, testcase.name) + set_show_tb(True) # Show traceback on crash. output = testcase.output if incremental: @@ -120,8 +120,11 @@ def run_case_once(self, testcase: DataDrivenTestCase, incremental=0) -> None: if incremental == 1: # In run 1, copy program text to program file. output = [] - with open(program_name, 'w') as f: - f.write(program_text) + for module_name, program_path, program_text in module_data: + if module_name == '__main__': + with open(program_path, 'w') as f: + f.write(program_text) + break elif incremental == 2: # In run 2, copy *.py.next files to *.py files. for dn, dirs, files in os.walk(os.curdir): @@ -130,11 +133,20 @@ def run_case_once(self, testcase: DataDrivenTestCase, incremental=0) -> None: full = os.path.join(dn, file) target = full[:-5] shutil.copy(full, target) - # Always set to none so we're forced to reread program_name - program_text = None - source = BuildSource(program_name, module_name, program_text) + + # In some systems, mtime has a resolution of 1 second which can cause + # annoying-to-debug issues when a file has the same size after a + # change. We manually set the mtime to circumvent this. + new_time = os.stat(target).st_mtime + 1 + os.utime(target, times=(new_time, new_time)) + + sources = [] + for module_name, program_path, program_text in module_data: + # Always set to none so we're forced to reread the module in incremental mode + program_text = None if incremental else program_text + sources.append(BuildSource(program_path, module_name, program_text)) try: - res = build.build(sources=[source], + res = build.build(sources=sources, options=options, alt_lib_path=test_temp_dir) a = res.errors @@ -152,14 +164,15 @@ def run_case_once(self, testcase: DataDrivenTestCase, incremental=0) -> None: testcase.file, testcase.line)) if incremental and res: - self.verify_cache(module_name, program_name, a, res.manager) + if not options.silent_imports: + self.verify_cache(module_data, a, res.manager) if testcase.expected_stale_modules is not None and incremental == 2: assert_string_arrays_equal( list(sorted(testcase.expected_stale_modules)), list(sorted(res.manager.stale_modules.difference({"__main__"}))), 'Set of stale modules does not match expected set') - def verify_cache(self, module_name: str, program_name: str, a: List[str], + def verify_cache(self, module_data: List[Tuple[str, str, str]], a: List[str], manager: build.BuildManager) -> None: # There should be valid cache metadata for each module except # those in error_paths; for those there should not be. @@ -169,7 +182,7 @@ def verify_cache(self, module_name: str, program_name: str, a: List[str], # However build.process_graphs() will ignore A's cache data. error_paths = self.find_error_paths(a) modules = self.find_module_files() - modules.update({module_name: program_name}) + modules.update({module_name: path for module_name, path, text in module_data}) missing_paths = self.find_missing_cache_files(modules, manager) if missing_paths != error_paths: raise AssertionFailure("cache data discrepancy %s != %s" % @@ -211,28 +224,40 @@ def find_missing_cache_files(self, modules: Dict[str, str], missing[id] = path return set(missing.values()) - def parse_module(self, program_text: str) -> Tuple[str, str, str]: + def parse_module(self, program_text: str, incremental: int = 0) -> List[Tuple[str, str, str]]: """Return the module and program names for a test case. - The default ('__main__') module name can be overridden by - using a comment like this in the test case input: + Normally, the unit tests will parse the default ('__main__') + module and follow all the imports listed there. You can override + this behavior and instruct the tests to check multiple modules + by using a comment like this in the test case input: - # cmd: mypy -m foo.bar + # cmd: mypy -m foo.bar foo.baz - Return tuple (main module name, main file name, main program text). + Return a list of tuples (module name, file name, program text). """ - m = re.search('# cmd: mypy -m ([a-zA-Z0-9_.]+) *$', program_text, flags=re.MULTILINE) + m = re.search('# cmd: mypy -m ([a-zA-Z0-9_. ]+)$', program_text, flags=re.MULTILINE) + m2 = re.search('# cmd2: mypy -m ([a-zA-Z0-9_. ]+)$', program_text, flags=re.MULTILINE) + if m2 is not None and incremental == 2: + # Optionally return a different command if in the second + # stage of incremental mode, otherwise default to reusing + # the original cmd. + m = m2 + if m: # The test case wants to use a non-default main # module. Look up the module and give it as the thing to # analyze. - module_name = m.group(1) - path = build.find_module(module_name, [test_temp_dir]) - with open(path) as f: - program_text = f.read() - return m.group(1), path, program_text + module_names = m.group(1) + out = [] + for module_name in module_names.split(' '): + path = build.find_module(module_name, [test_temp_dir]) + with open(path) as f: + program_text = f.read() + out.append((module_name, path, program_text)) + return out else: - return '__main__', 'main', program_text + return [('__main__', 'main', program_text)] def parse_options(self, program_text: str) -> Options: options = Options() diff --git a/mypy/test/testcmdline.py b/mypy/test/testcmdline.py index 9707f1456f59..d1ad9e76688e 100644 --- a/mypy/test/testcmdline.py +++ b/mypy/test/testcmdline.py @@ -44,6 +44,7 @@ def test_python_evaluation(testcase: DataDrivenTestCase) -> None: for s in testcase.input: file.write('{}\n'.format(s)) args = parse_args(testcase.input[0]) + args.append('--tb') # Show traceback on crash. # Type check the program. fixed = [python3_path, os.path.join(testcase.old_cwd, 'scripts', 'mypy')] diff --git a/mypy/test/testdocstring.py b/mypy/test/testdocstring.py deleted file mode 100644 index 9a6b67220007..000000000000 --- a/mypy/test/testdocstring.py +++ /dev/null @@ -1,147 +0,0 @@ -"""Test cases for finding type annotations in docstrings.""" - -from mypy.myunit import Suite, assert_equal -from mypy.docstring import parse_docstring, scrubtype - - -class DocstringSuite(Suite): - def test_scrubtype_basic(self): - assert_equal(scrubtype('int'), 'int') - assert_equal(scrubtype('FooBar'), 'FooBar') - assert_equal(scrubtype('List[str]'), 'List[str]') - - def test_scrubtype_aliases(self): - assert_equal(scrubtype('integer'), 'int') - assert_equal(scrubtype('an integer'), 'int') - assert_equal(scrubtype('dictionary'), 'Dict[Any, Any]') - - def test_scrubtype_patterns(self): - assert_equal(scrubtype('list of integer'), 'List[int]') - - def test_scrubtype_patterns_known_only(self): - - def check(source, expected): - assert_equal(scrubtype(source, only_known=True), expected) - - check('FooBar', None) - check('a FooBar', None) - check('int, int', None) - - check('None', 'None') - check('str', 'str') - check('Sequence[FooBar]', 'Sequence[FooBar]') - check('an integer', 'int') - check('list of integer', 'List[int]') - - def test_scrubtype_reject_parentheses(self): - assert_equal(scrubtype('('), None) - assert_equal(scrubtype(')'), None) - assert_equal(scrubtype('int (optional)'), None) - assert_equal(scrubtype('(optional) int'), None) - - def test_scrubtype_reject_curly_braces(self): - assert_equal(scrubtype('{'), None) - assert_equal(scrubtype('}'), None) - assert_equal(scrubtype('int {optional}'), None) - assert_equal(scrubtype('{optional} int'), None) - - def test_scrubtype_reject_comma_outside_brackets(self): - assert_equal(scrubtype('int, Optional'), None) - assert_equal(scrubtype('Tuple[int, int], or, Tuple[str, str]'), None) - - def test_no_annotations(self): - self.assert_no_annotation('') - self.assert_no_annotation('''foo\ - -List[int] bar''') - - def test_full_annotation(self): - self.assert_annotation('''Do something. - -Args: - x (int): An argument. - y (bool): Another argument. - More description. - z (str): Last argument. - -Returns: - Dict[str, int]: A dictionary. - -Raises: - IOError: Something happened. -''', {'x': 'int', 'y': 'bool', 'z': 'str'}, 'Dict[str, int]') - - def test_partial_annotations(self): - self.assert_annotation('''\ -Args: - x: list - y (str): dict - -Returns: - status''', {'x': None, 'y': 'str'}, None) - - def test_generic_types(self): - self.assert_annotation('''\ -Args: - x (List[int]): list - y (MyDict[int, List[str]]): dict - -Returns: - bool: status''', {'x': 'List[int]', 'y': 'MyDict[int, List[str]]'}, 'bool') - - def test_simple_return_with_no_description(self): - self.assert_annotation('''\ -Args: - x (an integer): a thing - -Returns: - an integer''', {'x': 'int'}, 'int') - self.assert_annotation('''\ -Args: - x (int): a thing -Returns: - FooBar''', {'x': 'int'}, None) - - def test_return_without_newline(self): - self.assert_annotation('''\ -Args: - x (int): a thing -Returns: - int''', {'x': 'int'}, 'int') - - def test_alternative_arg_headers(self): - self.assert_annotation('''\ -Arguments: - x (int): a thing -Returns: - int''', {'x': 'int'}, 'int') - self.assert_annotation('''\ -Params: - x (int): a thing -Returns: - int''', {'x': 'int'}, 'int') - self.assert_no_annotation('''\ -Parameters: - x (int): a thing -Returns: - int''') - - def test_only_args_no_return(self): - self.assert_annotation('''\ -Arguments: - x (int): a thing''', {'x': 'int'}, None) - - def test_only_arg_type_no_description(self): - self.skip() # TODO: Maybe get this to pass. - self.assert_annotation('''\ -Arguments: - x (int)''', {'x': 'int'}, None) - - def assert_no_annotation(self, docstring): - assert_equal(parse_docstring(docstring), None) - - def assert_annotation(self, docstring, args, rettype): - parsed = parse_docstring(docstring) - assert parsed is not None - assert_equal(parsed.args, args) - assert_equal(parsed.rettype, rettype) diff --git a/mypy/test/testpythoneval.py b/mypy/test/testpythoneval.py index d703ee1292e8..f5d94a8c8a94 100644 --- a/mypy/test/testpythoneval.py +++ b/mypy/test/testpythoneval.py @@ -62,6 +62,7 @@ def test_python_evaluation(testcase): interpreter = python3_path args = [] py2 = False + args.append('--tb') # Show traceback on crash. # Write the program to a file. program = '_program.py' program_path = os.path.join(test_temp_dir, program) diff --git a/mypy/test/testsemanal.py b/mypy/test/testsemanal.py index 74654ffcfba5..c2f7280db8f5 100644 --- a/mypy/test/testsemanal.py +++ b/mypy/test/testsemanal.py @@ -75,10 +75,10 @@ def test_semanal(testcase): # Omit the builtins module and files with a special marker in the # path. # TODO the test is not reliable - if (not f.path.endswith((os.sep + 'builtins.py', - 'typing.py', - 'abc.py', - 'collections.py')) + if (not f.path.endswith((os.sep + 'builtins.pyi', + 'typing.pyi', + 'abc.pyi', + 'collections.pyi')) and not os.path.basename(f.path).startswith('_') and not os.path.splitext( os.path.basename(f.path))[0].endswith('_')): diff --git a/mypy/test/testtransform.py b/mypy/test/testtransform.py index 410f4ebc1b38..bceee5c15b7e 100644 --- a/mypy/test/testtransform.py +++ b/mypy/test/testtransform.py @@ -60,9 +60,9 @@ def test_transform(testcase): # Omit the builtins module and files with a special marker in the # path. # TODO the test is not reliable - if (not f.path.endswith((os.sep + 'builtins.py', - 'typing.py', - 'abc.py')) + if (not f.path.endswith((os.sep + 'builtins.pyi', + 'typing.pyi', + 'abc.pyi')) and not os.path.basename(f.path).startswith('_') and not os.path.splitext( os.path.basename(f.path))[0].endswith('_')): diff --git a/mypy/typeanal.py b/mypy/typeanal.py index 3440a147cfec..447d1f06127b 100644 --- a/mypy/typeanal.py +++ b/mypy/typeanal.py @@ -201,7 +201,7 @@ def visit_instance(self, t: Instance) -> Type: return t def visit_type_var(self, t: TypeVarType) -> Type: - raise RuntimeError('TypeVarType is already analyzed') + return t def visit_callable_type(self, t: CallableType) -> Type: return t.copy_modified(arg_types=self.anal_array(t.arg_types), diff --git a/runtests.py b/runtests.py index 47db9407798c..8abc636a0206 100755 --- a/runtests.py +++ b/runtests.py @@ -77,6 +77,7 @@ def add_mypy_cmd(self, name: str, mypy_args: List[str], cwd: Optional[str] = Non if not self.allow(full_name): return args = [sys.executable, self.mypy] + mypy_args + args.append('--tb') # Show traceback on crash. self.waiter.add(LazySubprocess(full_name, args, cwd=cwd, env=self.env)) def add_mypy(self, name: str, *args: str, cwd: Optional[str] = None) -> None: diff --git a/test-data/unit/check-abstract.test b/test-data/unit/check-abstract.test index aa8e2062d271..05122f80df38 100644 --- a/test-data/unit/check-abstract.test +++ b/test-data/unit/check-abstract.test @@ -617,7 +617,7 @@ class B(A): def x(self) -> int: pass b = B() b.x() # E: "int" not callable -[builtins fixtures/property.py] +[builtins fixtures/property.pyi] [case testImplementReradWriteAbstractPropertyViaProperty] from abc import abstractproperty, ABCMeta @@ -633,7 +633,7 @@ class B(A): def x(self, v: int) -> None: pass b = B() b.x.y # E: "int" has no attribute "y" -[builtins fixtures/property.py] +[builtins fixtures/property.pyi] [case testImplementAbstractPropertyViaPropertyInvalidType] from abc import abstractproperty, ABCMeta @@ -645,7 +645,7 @@ class B(A): def x(self) -> str: pass # E b = B() b.x() # E -[builtins fixtures/property.py] +[builtins fixtures/property.pyi] [out] main: note: In class "B": main:7: error: Return type of "x" incompatible with supertype "A" @@ -662,7 +662,7 @@ class B(A): self.x = 1 # E b = B() # E b.x.y # E -[builtins fixtures/property.py] +[builtins fixtures/property.pyi] [out] main: note: In member "__init__" of class "B": main:7: error: Property "x" defined in "B" is read-only @@ -679,7 +679,7 @@ class B(A): @property def x(self) -> int: return super().x.y # E: "int" has no attribute "y" -[builtins fixtures/property.py] +[builtins fixtures/property.pyi] [out] main: note: In member "x" of class "B": @@ -697,7 +697,7 @@ class B(A): @x.setter def x(self, v: int) -> None: super().x = '' # E -[builtins fixtures/property.py] +[builtins fixtures/property.pyi] [out] main: note: In member "x" of class "B": main:10: error: "int" has no attribute "y" @@ -716,7 +716,7 @@ class B(A): def x(self) -> int: pass b = B() b.x.y # E -[builtins fixtures/property.py] +[builtins fixtures/property.pyi] [out] main: note: In class "B": main:8: error: Read-only property cannot override read-write property diff --git a/test-data/unit/check-async-await.test b/test-data/unit/check-async-await.test index 001d5218acd2..569a2995b52a 100644 --- a/test-data/unit/check-async-await.test +++ b/test-data/unit/check-async-await.test @@ -5,14 +5,14 @@ # options: fast_parser async def f() -> int: pass -[builtins fixtures/async_await.py] +[builtins fixtures/async_await.pyi] [case testAsyncDefReturn] # options: fast_parser async def f() -> int: return 0 reveal_type(f()) # E: Revealed type is 'typing.Awaitable[builtins.int]' -[builtins fixtures/async_await.py] +[builtins fixtures/async_await.pyi] [case testAwaitCoroutine] # options: fast_parser @@ -20,7 +20,7 @@ async def f() -> int: x = await f() reveal_type(x) # E: Revealed type is 'builtins.int*' return x -[builtins fixtures/async_await.py] +[builtins fixtures/async_await.pyi] [out] main: note: In function "f": @@ -92,7 +92,7 @@ def g() -> int: async def f() -> int: x = await g() return x -[builtins fixtures/async_await.py] +[builtins fixtures/async_await.pyi] [out] main: note: In function "f": main:5: error: Incompatible types in await (actual type "int", expected type "Awaitable") @@ -103,7 +103,7 @@ async def g() -> int: return 0 async def f() -> str: x = await g() # type: str -[builtins fixtures/async_await.py] +[builtins fixtures/async_await.pyi] [out] main: note: In function "f": main:5: error: Incompatible types in assignment (expression has type "int", variable has type "str") @@ -115,7 +115,7 @@ async def g() -> int: async def f() -> str: x = await g() return x -[builtins fixtures/async_await.py] +[builtins fixtures/async_await.pyi] [out] main: note: In function "f": main:6: error: Incompatible return value type (got "int", expected "str") @@ -128,7 +128,7 @@ class C(AsyncIterator[int]): async def f() -> None: async for x in C(): reveal_type(x) # E: Revealed type is 'builtins.int*' -[builtins fixtures/async_await.py] +[builtins fixtures/async_await.pyi] [out] main: note: In function "f": @@ -138,7 +138,7 @@ from typing import AsyncIterator async def f() -> None: async for x in [1]: pass -[builtins fixtures/async_await.py] +[builtins fixtures/async_await.pyi] [out] main: note: In function "f": main:4: error: AsyncIterable expected @@ -152,7 +152,7 @@ class C: async def f() -> None: async with C() as x: reveal_type(x) # E: Revealed type is 'builtins.int*' -[builtins fixtures/async_await.py] +[builtins fixtures/async_await.pyi] [out] main: note: In function "f": @@ -164,7 +164,7 @@ class C: async def f() -> None: async with C() as x: pass -[builtins fixtures/async_await.py] +[builtins fixtures/async_await.pyi] [out] main: note: In function "f": main:6: error: "C" has no attribute "__aenter__"; maybe "__enter__"? @@ -178,7 +178,7 @@ class C: async def f() -> None: async with C() as x: # E: Incompatible types in "async with" for __aenter__ (actual type "int", expected type "Awaitable") pass -[builtins fixtures/async_await.py] +[builtins fixtures/async_await.pyi] [out] main: note: In function "f": @@ -190,7 +190,7 @@ class C: async def f() -> None: async with C() as x: # E: "__aenter__" of "C" does not return a value pass -[builtins fixtures/async_await.py] +[builtins fixtures/async_await.pyi] [out] main: note: In function "f": @@ -202,7 +202,7 @@ class C: async def f() -> None: async with C() as x: # E: Incompatible types in "async with" for __aexit__ (actual type "int", expected type "Awaitable") pass -[builtins fixtures/async_await.py] +[builtins fixtures/async_await.pyi] [out] main: note: In function "f": @@ -214,7 +214,7 @@ class C: async def f() -> None: async with C() as x: # E: "__aexit__" of "C" does not return a value pass -[builtins fixtures/async_await.py] +[builtins fixtures/async_await.pyi] [out] main: note: In function "f": @@ -226,7 +226,7 @@ async def g(): yield async def h(): x = yield -[builtins fixtures/async_await.py] +[builtins fixtures/async_await.pyi] [out] main: note: In function "f": main:3: error: 'yield' in async function @@ -241,7 +241,7 @@ async def f(): yield from [] async def g(): x = yield from [] -[builtins fixtures/async_await.py] +[builtins fixtures/async_await.pyi] [out] main: note: In function "f": main:3: error: 'yield from' in async function @@ -261,7 +261,7 @@ async def f() -> str: def g() -> Generator[Any, None, str]: x = yield from f() return x -[builtins fixtures/async_await.py] +[builtins fixtures/async_await.pyi] [out] main: note: In function "g": main:6: error: "yield from" can't be applied to Awaitable[str] @@ -290,7 +290,7 @@ async def main() -> None: reveal_type(y) # E: Revealed type is 'builtins.int' async for z in I(): reveal_type(z) # E: Revealed type is 'builtins.int' -[builtins fixtures/async_await.py] +[builtins fixtures/async_await.pyi] [out] main: note: In function "main": @@ -307,7 +307,7 @@ def f() -> Generator[int, str, int]: return 0 else: return '' # E: Incompatible return value type (got "str", expected "int") -[builtins fixtures/async_await.py] +[builtins fixtures/async_await.pyi] [out] main: note: In function "f": @@ -397,5 +397,5 @@ async def decorated_host_coroutine() -> None: x = await other_iterator() # E: Incompatible types in await (actual type "It", expected type "Awaitable") x = await other_coroutine() -[builtins fixtures/async_await.py] +[builtins fixtures/async_await.pyi] [out] diff --git a/test-data/unit/check-basic.test b/test-data/unit/check-basic.test index 0812ccffece1..903470abecd9 100644 --- a/test-data/unit/check-basic.test +++ b/test-data/unit/check-basic.test @@ -223,21 +223,21 @@ import typing x = __name__ # type: str a = __name__ # type: A # E: Incompatible types in assignment (expression has type "str", variable has type "A") class A: pass -[builtins fixtures/primitives.py] +[builtins fixtures/primitives.pyi] [case testModule__doc__] import typing x = __doc__ # type: str a = __doc__ # type: A # E: Incompatible types in assignment (expression has type "str", variable has type "A") class A: pass -[builtins fixtures/primitives.py] +[builtins fixtures/primitives.pyi] [case testModule__file__] import typing x = __file__ # type: str a = __file__ # type: A # E: Incompatible types in assignment (expression has type "str", variable has type "A") class A: pass -[builtins fixtures/primitives.py] +[builtins fixtures/primitives.pyi] [case test__package__] import typing diff --git a/test-data/unit/check-bound.test b/test-data/unit/check-bound.test index a5bf3ca6302b..b17d787428f3 100644 --- a/test-data/unit/check-bound.test +++ b/test-data/unit/check-bound.test @@ -157,7 +157,7 @@ def f(x: T) -> T: return x b = f(B()) -[builtins fixtures/property.py] +[builtins fixtures/property.pyi] [out] main: note: In function "f": @@ -171,7 +171,7 @@ class A(A0): pass T = TypeVar('T', bound=A) def f(x: T) -> int: return x.foo(22) -[builtins fixtures/classmethod.py] +[builtins fixtures/classmethod.pyi] [case testBoundStaticMethod] @@ -184,7 +184,7 @@ class A(A0): pass T = TypeVar('T', bound=A) def f(x: T) -> int: return x.foo(22) -[builtins fixtures/staticmethod.py] +[builtins fixtures/staticmethod.pyi] [case testBoundOnDecorator] @@ -205,4 +205,4 @@ a = 1 b = foo(a) b = 'a' # E: Incompatible types in assignment (expression has type "str", variable has type "int") twice(a) # E: Type argument 1 of "twice" has incompatible value "int" -[builtins fixtures/args.py] +[builtins fixtures/args.pyi] diff --git a/test-data/unit/check-classes.test b/test-data/unit/check-classes.test index 3dba6e9b818c..7533c67ffaa9 100644 --- a/test-data/unit/check-classes.test +++ b/test-data/unit/check-classes.test @@ -483,7 +483,7 @@ class A: x = A() y = A() x = B() # E: Incompatible types in assignment (expression has type "B", variable has type "A") -[builtins fixtures/for.py] +[builtins fixtures/for.pyi] [out] main: note: In class "A": @@ -578,13 +578,13 @@ x = C.x # E: Cannot determine type of 'x' def f() -> int: return 1 class C: x = f() -[builtins fixtures/list.py] +[builtins fixtures/list.pyi] [case testAccessingClassAttributeWithTypeInferenceIssue2] class C: x = [] x = C.x -[builtins fixtures/list.py] +[builtins fixtures/list.pyi] [out] main: note: In class "C": main:2: error: Need type annotation for variable @@ -689,7 +689,7 @@ class A: class B: 'x' y = B() -[builtins fixtures/primitives.py] +[builtins fixtures/primitives.pyi] [case testErrorMessageInFunctionNestedWithinMethod] import typing @@ -718,13 +718,13 @@ A.f(1) A().f(1) A.f('') # E: Argument 1 to "f" of "A" has incompatible type "str"; expected "int" A().f('') # E: Argument 1 to "f" of "A" has incompatible type "str"; expected "int" -[builtins fixtures/staticmethod.py] +[builtins fixtures/staticmethod.pyi] [case testBuiltinStaticMethod] import typing int.from_bytes(b'', '') int.from_bytes('', '') # E: Argument 1 to "from_bytes" of "int" has incompatible type "str"; expected "bytes" -[builtins fixtures/staticmethod.py] +[builtins fixtures/staticmethod.pyi] [case testAssignStaticMethodOnInstance] import typing @@ -732,7 +732,7 @@ class A: @staticmethod def f(x: int) -> None: pass A().f = A.f # E: Cannot assign to a method -[builtins fixtures/staticmethod.py] +[builtins fixtures/staticmethod.pyi] -- Class methods @@ -748,13 +748,13 @@ A.f(1) A().f(1) A.f('') # E: Argument 1 to "f" of "A" has incompatible type "str"; expected "int" A().f('') # E: Argument 1 to "f" of "A" has incompatible type "str"; expected "int" -[builtins fixtures/classmethod.py] +[builtins fixtures/classmethod.pyi] [case testBuiltinClassMethod] import typing int.from_bytes(b'', '') int.from_bytes('', '') # E: Argument 1 to "from_bytes" of "int" has incompatible type "str"; expected "bytes" -[builtins fixtures/classmethod.py] +[builtins fixtures/classmethod.pyi] [case testAssignClassMethodOnClass] import typing @@ -762,7 +762,7 @@ class A: @classmethod def f(cls, x: int) -> None: pass A.f = A.f # E: Cannot assign to a method -[builtins fixtures/classmethod.py] +[builtins fixtures/classmethod.pyi] [case testAssignClassMethodOnInstance] import typing @@ -770,7 +770,7 @@ class A: @classmethod def f(cls, x: int) -> None: pass A().f = A.f # E: Cannot assign to a method -[builtins fixtures/classmethod.py] +[builtins fixtures/classmethod.pyi] [case testClassMethodCalledInClassMethod] import typing @@ -784,7 +784,7 @@ class C: cls.bar() cls.bar(1) # E: Too many arguments for "bar" of "C" cls.bozo() # E: "C" has no attribute "bozo" -[builtins fixtures/classmethod.py] +[builtins fixtures/classmethod.pyi] [out] main: note: In member "bar" of class "C": @@ -796,7 +796,7 @@ class C: C.foo() C.foo(1) # E: Too many arguments for "foo" of "C" C.bozo() # E: "C" has no attribute "bozo" -[builtins fixtures/classmethod.py] +[builtins fixtures/classmethod.pyi] [case testClassMethodCalledOnInstance] import typing @@ -806,7 +806,7 @@ class C: C().foo() C().foo(1) # E: Too many arguments for "foo" of "C" C.bozo() # E: "C" has no attribute "bozo" -[builtins fixtures/classmethod.py] +[builtins fixtures/classmethod.pyi] [case testClassMethodMayCallAbstractMethod] from abc import abstractmethod @@ -818,7 +818,7 @@ class C: @abstractmethod def bar(self) -> None: pass -[builtins fixtures/classmethod.py] +[builtins fixtures/classmethod.pyi] -- Properties @@ -834,7 +834,7 @@ a = A() # type. A s = '' # type: str s = a.f a = a.f # E: Incompatible types in assignment (expression has type "str", variable has type "A") -[builtins fixtures/property.py] +[builtins fixtures/property.pyi] [case testAssigningToReadOnlyProperty] import typing @@ -842,7 +842,7 @@ class A: @property def f(self) -> str: pass A().f = '' # E: Property "f" defined in "A" is read-only -[builtins fixtures/property.py] +[builtins fixtures/property.pyi] [case testPropertyGetterBody] import typing @@ -851,7 +851,7 @@ class A: def f(self) -> str: self.x = 1 self.x = '' # E: Incompatible types in assignment (expression has type "str", variable has type "int") -[builtins fixtures/property.py] +[builtins fixtures/property.pyi] [out] main: note: In member "f" of class "A": @@ -863,7 +863,7 @@ class A: a = A() # type. A a.f.xx a.f = '' # E: Property "f" defined in "A" is read-only -[builtins fixtures/property.py] +[builtins fixtures/property.pyi] [case testPropertyWithSetter] import typing @@ -878,7 +878,7 @@ a = A() a.f = a.f a.f.x # E: "int" has no attribute "x" a.f = '' # E: Incompatible types in assignment (expression has type "str", variable has type "int") -[builtins fixtures/property.py] +[builtins fixtures/property.pyi] [case testPropertyWithDeleterButNoSetter] import typing @@ -892,7 +892,7 @@ class A: a = A() a.f = a.f # E: Property "f" defined in "A" is read-only a.f.x # E: "int" has no attribute "x" -[builtins fixtures/property.py] +[builtins fixtures/property.pyi] -- Multiple inheritance, non-object built-in class as base @@ -951,7 +951,7 @@ def g(x: complex) -> None: pass f(1) g(1) g(1.1) -[builtins fixtures/complex.py] +[builtins fixtures/complex.pyi] -- Operator methods @@ -1289,7 +1289,7 @@ class C: x = C(foo=12) x.a # E: "C" has no attribute "a" C(foo='') # E: Argument 1 to "C" has incompatible type "str"; expected "int" -[builtins fixtures/__new__.py] +[builtins fixtures/__new__.pyi] [case testConstructInstanceWithDynamicallyTyped__new__] class C: @@ -1301,7 +1301,7 @@ x = C(foo=12) x = C(foo='x') x.a # E: "C" has no attribute "a" C(bar='') # E: Unexpected keyword argument "bar" for "C" -[builtins fixtures/__new__.py] +[builtins fixtures/__new__.pyi] [case testClassWith__new__AndCompatibilityWithType] class C: @@ -1312,7 +1312,7 @@ def f(x: type) -> None: pass def g(x: int) -> None: pass f(C) g(C) # E: Argument 1 to "g" has incompatible type "C"; expected "int" -[builtins fixtures/__new__.py] +[builtins fixtures/__new__.pyi] [case testClassWith__new__AndCompatibilityWithType2] class C: @@ -1323,7 +1323,7 @@ def f(x: type) -> None: pass def g(x: int) -> None: pass f(C) g(C) # E: Argument 1 to "g" has incompatible type "C"; expected "int" -[builtins fixtures/__new__.py] +[builtins fixtures/__new__.pyi] [case testGenericClassWith__new__] from typing import TypeVar, Generic @@ -1336,7 +1336,7 @@ class C(Generic[T]): c = C('') c.set('') c.set(1) # E: Argument 1 to "set" of "C" has incompatible type "int"; expected "str" -[builtins fixtures/__new__.py] +[builtins fixtures/__new__.pyi] [case testOverloaded__new__] from typing import overload @@ -1353,7 +1353,7 @@ c = C(1) c.a # E: "C" has no attribute "a" C('', '') C('') # E: No overload variant of "C" matches argument types [builtins.str] -[builtins fixtures/__new__.py] +[builtins fixtures/__new__.pyi] -- Special cases @@ -1577,7 +1577,7 @@ class X: pass def bar(arg: Type[X]): foo(arg) foo(X) -[builtins fixtures/tuple.py] +[builtins fixtures/tuple.pyi] [out] [case testTypeUsingTypeCClassMethod] @@ -1592,7 +1592,7 @@ def process(cls: Type[User]): reveal_type(cls.bar(obj)) # E: Revealed type is 'builtins.int' cls.mro() # Defined in class type cls.error # E: Type[User] has no attribute "error" -[builtins fixtures/classmethod.py] +[builtins fixtures/classmethod.pyi] [out] main: note: In function "process": @@ -1611,7 +1611,7 @@ def process(cls: Type[Union[BasicUser, ProUser]]): cls.bar(obj) # E: Type[Union[BasicUser, ProUser]] has no attribute "bar" cls.mro() # Defined in class type cls.error # E: Type[Union[BasicUser, ProUser]] has no attribute "error" -[builtins fixtures/classmethod.py] +[builtins fixtures/classmethod.pyi] [out] main: note: In function "process": @@ -1628,7 +1628,7 @@ def process(cls: Type[U]): reveal_type(cls.bar(obj)) # E: Revealed type is 'builtins.int' cls.mro() # Defined in class type cls.error # E: Type[U] has no attribute "error" -[builtins fixtures/classmethod.py] +[builtins fixtures/classmethod.pyi] [out] main: note: In function "process": @@ -1648,7 +1648,7 @@ def process(cls: Type[U]): cls.bar(obj) # E: Type[U] has no attribute "bar" cls.mro() # Defined in class type cls.error # E: Type[U] has no attribute "error" -[builtins fixtures/classmethod.py] +[builtins fixtures/classmethod.pyi] [out] main: note: In function "process": @@ -1656,7 +1656,7 @@ main: note: In function "process": from typing import Type, Tuple def foo(arg: Type[Tuple[int]]): # E: Unsupported type Type["Tuple[int]"] arg() -[builtins fixtures/tuple.py] +[builtins fixtures/tuple.pyi] [out] main: note: In function "foo": @@ -1680,7 +1680,7 @@ def new(uc: Type[U]) -> U: u.foo(0) return uc() u = new(User) -[builtins fixtures/classmethod.py] +[builtins fixtures/classmethod.pyi] [out] main: note: In function "new": main:16: error: No overload variant of "User" matches argument types [builtins.str] @@ -1706,7 +1706,7 @@ from typing import Type, NamedTuple N = NamedTuple('N', [('x', int), ('y', int)]) def f(a: Type[N]): a() -[builtins fixtures/list.py] +[builtins fixtures/list.pyi] [out] main: note: In function "f": main:3: error: Unsupported type Type["N"] @@ -1720,7 +1720,7 @@ def foo(c: Type[C], d: Type[D]) -> None: x = [c, d] reveal_type(x) -[builtins fixtures/list.py] +[builtins fixtures/list.pyi] [out] main: note: In function "foo": main:7: error: Revealed type is 'builtins.list[Type[__main__.B]]' @@ -1738,7 +1738,7 @@ def f(a: int) -> str: pass reveal_type(f(User)) # E: Revealed type is 'builtins.int' reveal_type(f(UserType)) # E: Revealed type is 'builtins.int' -[builtins fixtures/classmethod.py] +[builtins fixtures/classmethod.pyi] [out] [case testTypeMatchesGeneralTypeInOverloadedFunctions] @@ -1757,7 +1757,7 @@ def f(a: int) -> str: reveal_type(f(User)) # E: Revealed type is 'builtins.int' reveal_type(f(UserType)) # E: Revealed type is 'builtins.int' reveal_type(f(1)) # E: Revealed type is 'builtins.str' -[builtins fixtures/classmethod.py] +[builtins fixtures/classmethod.pyi] [out] [case testTypeMatchesSpecificTypeInOverloadedFunctions] @@ -1780,7 +1780,7 @@ reveal_type(f(User)) # E: Revealed type is 'builtins.int' reveal_type(f(UserType)) # E: Revealed type is 'builtins.int' reveal_type(f(User())) # E: Revealed type is '__main__.User' reveal_type(f(1)) # E: Revealed type is 'builtins.str' -[builtins fixtures/classmethod.py] +[builtins fixtures/classmethod.pyi] [out] [case testMixingTypeTypeInOverloadedFunctions] @@ -1805,7 +1805,7 @@ reveal_type(f(User())) # E: Revealed type is 'Type[__main__.User]' reveal_type(f(User)) # E: Revealed type is '__main__.User' reveal_type(f(3)) # E: Revealed type is 'Type[__main__.User]' reveal_type(f("hi")) # E: Revealed type is '__main__.User' -[builtins fixtures/classmethod.py] +[builtins fixtures/classmethod.pyi] [out] [case testGeneralTypeDoesNotMatchSpecificTypeInOverloadedFunctions] @@ -1822,7 +1822,7 @@ def mock() -> type: return User f(User) f(mock()) # E: No overload variant of "f" matches argument types [builtins.type] -[builtins fixtures/classmethod.py] +[builtins fixtures/classmethod.pyi] [out] [case testNonTypeDoesNotMatchOverloadedFunctions] @@ -1836,7 +1836,7 @@ def f(a: Type[User]) -> None: pass def f(a: type) -> None: pass f(3) # E: No overload variant of "f" matches argument types [builtins.int] -[builtins fixtures/classmethod.py] +[builtins fixtures/classmethod.pyi] [out] [case testInstancesDoNotMatchTypeInOverloadedFunctions] @@ -1851,7 +1851,7 @@ def f(a: int) -> None: pass f(User) f(User()) # E: No overload variant of "f" matches argument types [__main__.User] -[builtins fixtures/classmethod.py] +[builtins fixtures/classmethod.pyi] [out] [case testTypeCovarianceWithOverloadedFunctions] @@ -1875,7 +1875,7 @@ f(C) f(AType) # E: No overload variant of "f" matches argument types [Type[__main__.A]] f(BType) f(CType) -[builtins fixtures/classmethod.py] +[builtins fixtures/classmethod.pyi] [out] @@ -1889,7 +1889,7 @@ class B(A): pass def f(a: Type[A]) -> int: pass # E: Overloaded function signatures 1 and 2 overlap with incompatible return types @overload def f(a: Type[B]) -> str: pass -[builtins fixtures/classmethod.py] +[builtins fixtures/classmethod.pyi] [out] [case testDistinctOverloadedCovariantTypesSucceed] @@ -1918,7 +1918,7 @@ reveal_type(f(A())) # E: Revealed type is '__main__.A' reveal_type(f(AChild())) # E: Revealed type is '__main__.A' reveal_type(f(B())) # E: Revealed type is '__main__.B' reveal_type(f(BChild())) # E: Revealed type is '__main__.B' -[builtins fixtures/classmethod.py] +[builtins fixtures/classmethod.pyi] [out] [case testTypeTypeOverlapsWithObjectAndType] @@ -1935,7 +1935,7 @@ def f(a: object) -> str: pass def g(a: Type[User]) -> int: pass # E: Overloaded function signatures 1 and 2 overlap with incompatible return types @overload def g(a: type) -> str: pass -[builtins fixtures/classmethod.py] +[builtins fixtures/classmethod.pyi] [out] [case testTypeOverlapsWithObject] @@ -1947,7 +1947,7 @@ class User: pass def f(a: type) -> int: pass # E: Overloaded function signatures 1 and 2 overlap with incompatible return types @overload def f(a: object) -> str: pass -[builtins fixtures/classmethod.py] +[builtins fixtures/classmethod.pyi] [out] [case testTypeConstructorReturnsTypeType] @@ -1964,7 +1964,7 @@ reveal_type(type(u)) # E: Revealed type is 'Type[__main__.User]' reveal_type(type(u).test_class_method()) # E: Revealed type is 'builtins.int' reveal_type(type(u).test_static_method()) # E: Revealed type is 'builtins.str' type(u).test_instance_method() # E: Too few arguments for "test_instance_method" of "User" -[builtins fixtures/classmethod.py] +[builtins fixtures/classmethod.pyi] [out] [case testObfuscatedTypeConstructorReturnsTypeType] @@ -1981,7 +1981,7 @@ u = User() reveal_type(f1(u)) # E: Revealed type is 'Type[__main__.User]' reveal_type(f2(type)(u)) # E: Revealed type is 'Type[__main__.User]' -[builtins fixtures/classmethod.py] +[builtins fixtures/classmethod.pyi] [out] [case testTypeConstructorLookalikeFails] @@ -1995,7 +1995,7 @@ def fake2(a: int) -> type: reveal_type(type(User())) # E: Revealed type is 'Type[__main__.User]' reveal_type(fake1(User())) # E: Revealed type is 'builtins.type' reveal_type(fake2(3)) # E: Revealed type is 'builtins.type' -[builtins fixtures/classmethod.py] +[builtins fixtures/classmethod.pyi] [out] [case testOtherTypeConstructorsSucceed] @@ -2003,7 +2003,7 @@ def foo(self) -> int: return self.attr User = type('User', (object,), {'foo': foo, 'attr': 3}) reveal_type(User) # E: Revealed type is 'builtins.type' -[builtins fixtures/args.py] +[builtins fixtures/args.pyi] [out] [case testTypeTypeComparisonWorks] @@ -2041,7 +2041,7 @@ type(3) is type(3) int.__eq__(int) int.__eq__(3, 4) -[builtins fixtures/args.py] +[builtins fixtures/args.pyi] [out] main:33: error: Too few arguments for "__eq__" of "int" main:33: error: Unsupported operand types for == ("int" and "int") @@ -2059,3 +2059,9 @@ class B(A): pass class C(B): pass class D(A, B): pass # E: Cannot determine consistent method resolution order (MRO) for "D" class E(C, D): pass # E: Cannot determine consistent method resolution order (MRO) for "E" + +[case testInconsistentMroLocalRef] +class A: pass +class B(object, A): # E: Cannot determine consistent method resolution order (MRO) for "B" + def readlines(self): pass + __iter__ = readlines diff --git a/test-data/unit/check-dynamic-typing.test b/test-data/unit/check-dynamic-typing.test index 8f41e2ed6260..6384006102f3 100644 --- a/test-data/unit/check-dynamic-typing.test +++ b/test-data/unit/check-dynamic-typing.test @@ -178,7 +178,7 @@ a = not d # E: Incompatible types in assignment (expression has type "bool", var b = not d a = -d class A: pass -[builtins fixtures/bool.py] +[builtins fixtures/bool.pyi] [out] [case testDynamicWithMemberAccess] @@ -219,7 +219,7 @@ t2 = (d, d, d) # E: Incompatible types in assignment (expression has type "Tupl t2 = (d, d) class A: pass -[builtins fixtures/tuple.py] +[builtins fixtures/tuple.pyi] [case testCastsWithDynamicType] from typing import Any, cast @@ -252,7 +252,7 @@ def g(a: 'A') -> None: class A: pass class B: pass -[builtins fixtures/tuple.py] +[builtins fixtures/tuple.pyi] -- Statements @@ -268,13 +268,13 @@ if d: pass elif d: pass -[builtins fixtures/bool.py] +[builtins fixtures/bool.pyi] [case testRaiseWithDynamic] from typing import Any d = None # type: Any raise d -[builtins fixtures/exception.py] +[builtins fixtures/exception.pyi] [case testReturnWithDynamic] from typing import Any @@ -389,7 +389,7 @@ def g(x): if a(): a() class A: pass -[builtins fixtures/bool.py] +[builtins fixtures/bool.pyi] [case testSkipTypeCheckingWithImplicitSignatureAndDefaultArgs] @@ -462,7 +462,7 @@ f() # E: Too few arguments for "f" f(o) f(o, o) f(o, o, o) -[builtins fixtures/list.py] +[builtins fixtures/list.pyi] -- Implicit types for constructors @@ -528,7 +528,7 @@ t4 = t2 t4 = t3 class A: pass -[builtins fixtures/tuple.py] +[builtins fixtures/tuple.pyi] [case testFunctionTypeCompatibilityAndReturnTypes] from typing import Any, Callable diff --git a/test-data/unit/check-expressions.test b/test-data/unit/check-expressions.test index 9f89ba3dcae9..ccd4ee9ef402 100644 --- a/test-data/unit/check-expressions.test +++ b/test-data/unit/check-expressions.test @@ -99,7 +99,7 @@ s = None # type: str s = u'foo' b = None # type: bytes b = u'foo' # E: Incompatible types in assignment (expression has type "str", variable has type "bytes") -[builtins fixtures/primitives.py] +[builtins fixtures/primitives.pyi] -- Binary operators @@ -301,7 +301,7 @@ b = b or a # E: Incompatible types in assignment (expression has type "Union[bo b = a or b # E: Incompatible types in assignment (expression has type "Union[A, bool]", variable has type "bool") class A: pass -[builtins fixtures/bool.py] +[builtins fixtures/bool.pyi] [case testRestrictedTypeAnd] @@ -312,7 +312,7 @@ if j: reveal_type(j) # E: Revealed type is 'builtins.str' -[builtins fixtures/bool.py] +[builtins fixtures/bool.pyi] [case testRestrictedTypeOr] @@ -322,7 +322,7 @@ j = b or i if not j: reveal_type(j) # E: Revealed type is 'builtins.str' -[builtins fixtures/bool.py] +[builtins fixtures/bool.pyi] [case testNonBooleanOr] @@ -335,7 +335,7 @@ d = c or d # E: Incompatible types in assignment (expression has type "C", varia d = d or c # E: Incompatible types in assignment (expression has type "C", variable has type "D") class C: pass class D(C): pass -[builtins fixtures/bool.py] +[builtins fixtures/bool.pyi] [case testInOperator] from typing import Iterator, Iterable, Any @@ -354,7 +354,7 @@ class A: class B: pass class D(Iterable[A]): def __iter__(self) -> Iterator[A]: pass -[builtins fixtures/bool.py] +[builtins fixtures/bool.pyi] [out] main:3: error: Unsupported operand types for in ("bool" and "A") main:4: error: Incompatible types in assignment (expression has type "bool", variable has type "A") @@ -378,7 +378,7 @@ class A: class B: pass class D(Iterable[A]): def __iter__(self) -> Iterator[A]: pass -[builtins fixtures/bool.py] +[builtins fixtures/bool.pyi] [out] main:3: error: Unsupported operand types for in ("bool" and "A") main:4: error: Incompatible types in assignment (expression has type "bool", variable has type "A") @@ -393,7 +393,7 @@ b = a in a class A: def __contains__(self, x: 'A') -> object: pass -[builtins fixtures/bool.py] +[builtins fixtures/bool.pyi] [out] main:4: error: Incompatible types in assignment (expression has type "object", variable has type "bool") @@ -408,7 +408,7 @@ b = a != b class A: def __eq__(self, o: object) -> bool: pass def __ne__(self, o: object) -> bool: pass -[builtins fixtures/bool.py] +[builtins fixtures/bool.pyi] [out] main:3: error: Incompatible types in assignment (expression has type "bool", variable has type "A") main:4: error: Incompatible types in assignment (expression has type "bool", variable has type "A") @@ -427,7 +427,7 @@ class A: class B: def __lt__(self, o: 'B') -> bool: pass def __gt__(self, o: 'B') -> bool: pass -[builtins fixtures/bool.py] +[builtins fixtures/bool.pyi] [out] main:3: error: Incompatible types in assignment (expression has type "bool", variable has type "A") main:4: error: Incompatible types in assignment (expression has type "bool", variable has type "A") @@ -446,7 +446,7 @@ class A: class B: def __le__(self, o: 'B') -> bool: pass def __ge__(self, o: 'B') -> bool: pass -[builtins fixtures/bool.py] +[builtins fixtures/bool.pyi] [out] main:3: error: Incompatible types in assignment (expression has type "bool", variable has type "A") main:4: error: Incompatible types in assignment (expression has type "bool", variable has type "A") @@ -464,7 +464,7 @@ class A: class B: def __lt__(self, o: 'B') -> bool: pass def __gt__(self, o: 'B') -> bool: pass -[builtins fixtures/bool.py] +[builtins fixtures/bool.pyi] [out] main:3: error: Unsupported operand types for > ("A" and "A") main:5: error: Unsupported operand types for > ("A" and "A") @@ -483,7 +483,7 @@ class A: class B: def __lt__(self, o: 'B') -> bool: pass def __gt__(self, o: 'B') -> bool: pass -[builtins fixtures/bool.py] +[builtins fixtures/bool.pyi] [out] main:4: error: Incompatible types in assignment (expression has type "bool", variable has type "A") @@ -512,7 +512,7 @@ class Y: def __lt__(self, o: 'Y') -> A: pass def __gt__(self, o: 'Y') -> A: pass def __eq__(self, o: 'Y') -> B: pass -[builtins fixtures/bool.py] +[builtins fixtures/bool.pyi] [out] main:5: error: Incompatible types in assignment (expression has type "B", variable has type "bool") main:7: error: Incompatible types in assignment (expression has type "P", variable has type "A") @@ -526,7 +526,7 @@ b = a is b b = b is a b = a is None class A: pass -[builtins fixtures/bool.py] +[builtins fixtures/bool.pyi] [out] main:3: error: Incompatible types in assignment (expression has type "bool", variable has type "A") @@ -538,7 +538,7 @@ b = a is not b b = b is not a b = a is not None class A: pass -[builtins fixtures/bool.py] +[builtins fixtures/bool.pyi] [out] main:3: error: Incompatible types in assignment (expression has type "bool", variable has type "A") @@ -678,7 +678,7 @@ b = not a b = not b class A: pass -[builtins fixtures/bool.py] +[builtins fixtures/bool.pyi] [out] main:3: error: Incompatible types in assignment (expression has type "bool", variable has type "A") @@ -816,7 +816,7 @@ def g() -> object: return f() # Fail def f() -> None: pass -[builtins fixtures/exception.py] +[builtins fixtures/exception.pyi] [out] main:2: error: "f" does not return a value main:3: error: "f" does not return a value @@ -839,7 +839,7 @@ f().foo # E: "f" does not return a value def f() -> None: pass class A: def __add__(self, x: 'A') -> 'A': pass -[builtins fixtures/list.py] +[builtins fixtures/list.pyi] [case testNoneReturnTypeWithExpressions2] @@ -857,7 +857,7 @@ def f() -> None: pass class A: def __add__(self, x: 'A') -> 'A': pass -[builtins fixtures/bool.py] +[builtins fixtures/bool.pyi] -- Slicing @@ -880,7 +880,7 @@ b = a[:] class A: def __getitem__(self, s: slice) -> 'B': pass class B: pass -[builtins fixtures/slice.py] +[builtins fixtures/slice.pyi] [case testSlicingWithInvalidBase] @@ -889,14 +889,14 @@ a[1:2] # E: Invalid index type "slice" for "A" a[:] # E: Invalid index type "slice" for "A" class A: def __getitem__(self, n: int) -> 'A': pass -[builtins fixtures/slice.py] +[builtins fixtures/slice.pyi] [case testSlicingWithNonindexable] o = None # type: object o[1:2] # E: Value of type "object" is not indexable o[:] # E: Value of type "object" is not indexable -[builtins fixtures/slice.py] +[builtins fixtures/slice.pyi] [case testNonIntSliceBounds] from typing import Any @@ -905,7 +905,7 @@ a[o:1] # E: Slice index must be an integer or None a[1:o] # E: Slice index must be an integer or None a[o:] # E: Slice index must be an integer or None a[:o] # E: Slice index must be an integer or None -[builtins fixtures/slice.py] +[builtins fixtures/slice.pyi] [case testNoneSliceBounds] from typing import Any @@ -914,7 +914,7 @@ a[None:1] a[1:None] a[None:] a[:None] -[builtins fixtures/slice.py] +[builtins fixtures/slice.pyi] -- String interpolation @@ -932,13 +932,13 @@ i, f, s, t = None, None, None, None # type: (int, float, str, Tuple[int]) '%d' % t '%d' % s # E: Incompatible types in string interpolation (expression has type "str", placeholder has type "Union[int, float]") '%f' % s # E: Incompatible types in string interpolation (expression has type "str", placeholder has type "Union[int, float]") -[builtins fixtures/primitives.py] +[builtins fixtures/primitives.pyi] [case testStringInterpolationSAcceptsAnyType] from typing import Any i, o, s = None, None, None # type: (int, object, str) '%s %s %s' % (i, o, s) -[builtins fixtures/primitives.py] +[builtins fixtures/primitives.pyi] [case testStringInterpolationCount] '%d %d' % 1 # E: Not enough arguments for format string @@ -948,13 +948,13 @@ t = 1, 's' '%d %s' % t '%s %d' % t # E: Incompatible types in string interpolation (expression has type "str", placeholder has type "Union[int, float]") '%d' % t # E: Not all arguments converted during string formatting -[builtins fixtures/primitives.py] +[builtins fixtures/primitives.pyi] [case testStringInterpolationWithAnyType] from typing import Any a = None # type: Any '%d %d' % a -[builtins fixtures/primitives.py] +[builtins fixtures/primitives.pyi] [case testStringInterpolationInvalidPlaceholder] '%W' % 1 # E: Unsupported format character 'W' @@ -964,14 +964,14 @@ a = None # type: Any '%*f' % 3.14 # E: Not enough arguments for format string '%*f' % (4, 3.14) '%*f' % (1.1, 3.14) # E: * wants int -[builtins fixtures/primitives.py] +[builtins fixtures/primitives.pyi] [case testStringInterpolationPrecision] '%.2f' % 3.14 '%.*f' % 3.14 # E: Not enough arguments for format string '%.*f' % (4, 3.14) '%.*f' % (1.1, 3.14) # E: * wants int -[builtins fixtures/primitives.py] +[builtins fixtures/primitives.pyi] [case testStringInterpolationWidthAndPrecision] '%4.2f' % 3.14 @@ -979,33 +979,33 @@ a = None # type: Any '%*.2f' % 3.14 # E: Not enough arguments for format string '%*.*f' % 3.14 # E: Not enough arguments for format string '%*.*f' % (4, 2, 3.14) -[builtins fixtures/primitives.py] +[builtins fixtures/primitives.pyi] [case testStringInterpolationFlagsAndLengthModifiers] '%04hd' % 1 '%-.4ld' % 1 '%+*Ld' % (1, 1) '% .*ld' % (1, 1) -[builtins fixtures/primitives.py] +[builtins fixtures/primitives.pyi] [case testStringInterpolationDoublePercentage] '%% %d' % 1 '%3% %d' % 1 '%*%' % 1 '%*% %d' % 1 # E: Not enough arguments for format string -[builtins fixtures/primitives.py] +[builtins fixtures/primitives.pyi] [case testStringInterpolationC] '%c' % 1 '%c' % 's' '%c' % '' # E: %c requires int or char '%c' % 'ab' # E: %c requires int or char -[builtins fixtures/primitives.py] +[builtins fixtures/primitives.pyi] [case testStringInterpolationMappingTypes] '%(a)d %(b)s' % {'a': 1, 'b': 's'} '%(a)d %(b)s' % {'a': 's', 'b': 1} # E: Incompatible types in string interpolation (expression has type "str", placeholder with key 'a' has type "Union[int, float]") -[builtins fixtures/primitives.py] +[builtins fixtures/primitives.pyi] [case testStringInterpolationMappingKeys] '%()d' % {'': 2} @@ -1013,7 +1013,7 @@ a = None # type: Any '%(q)d' % {'a': 1, 'b': 2, 'c': 3} # E: Key 'q' not found in mapping '%(a)d %%' % {'a': 1} -[builtins fixtures/dict.py] +[builtins fixtures/dict.pyi] [case testStringInterpolationMappingDictTypes] from typing import Any, Dict @@ -1023,13 +1023,13 @@ ds, do, di = None, None, None # type: Dict[str, int], Dict[object, int], Dict[in '%()d' % a '%()d' % ds '%()d' % do -[builtins fixtures/dict.py] +[builtins fixtures/dict.pyi] [case testStringInterpolationMappingInvalidDictTypes-skip] from typing import Any, Dict di = None # type: Dict[int, int] '%()d' % di # E: Format requires a mapping (expression has type Dict[int, int], expected type for mapping is Dict[str, Any]) -[builtins fixtures/dict.py] +[builtins fixtures/dict.pyi] [case testStringInterpolationMappingInvalidSpecifiers] '%(a)d %d' % 1 # E: String interpolation mixes specifier with and without mapping keys @@ -1040,14 +1040,14 @@ di = None # type: Dict[int, int] '%(a)1d' % {'a': 1} '%(a).1d' % {'a': 1} '%(a)#1.1ld' % {'a': 1} -[builtins fixtures/dict.py] +[builtins fixtures/dict.pyi] [case testStringInterpolationFloatPrecision] '%.f' % 1.2 '%.3f' % 1.2 '%.f' % 'x' '%.3f' % 'x' -[builtins fixtures/primitives.py] +[builtins fixtures/primitives.pyi] [out] main:3: error: Incompatible types in string interpolation (expression has type "str", placeholder has type "Union[int, float]") main:4: error: Incompatible types in string interpolation (expression has type "str", placeholder has type "Union[int, float]") @@ -1085,7 +1085,7 @@ a = [x for x in a] b = [x for x in a] # type: List[B] # E: List comprehension has incompatible type List[A] class A: pass class B: pass -[builtins fixtures/for.py] +[builtins fixtures/for.pyi] [case testSimpleListComprehensionNestedTuples] from typing import List, Tuple @@ -1094,7 +1094,7 @@ a = [a2 for a1, (a2, b1) in l] # type: List[A] b = [a2 for a1, (a2, b1) in l] # type: List[B] # E: List comprehension has incompatible type List[A] class A: pass class B: pass -[builtins fixtures/for.py] +[builtins fixtures/for.pyi] [case testSimpleListComprehensionNestedTuples2] from typing import List, Tuple @@ -1103,7 +1103,7 @@ a = [f(d) for d, (i, s) in l] b = [f(s) for d, (i, s) in l] # E: Argument 1 to "f" has incompatible type "str"; expected "int" def f(x: int): pass -[builtins fixtures/for.py] +[builtins fixtures/for.pyi] [case testListComprehensionWithNonDirectMapping] from typing import List @@ -1115,21 +1115,21 @@ a = [f(x) for x in a] # E: List comprehension has incompatible type List[B] class A: pass class B: pass def f(a: A) -> B: pass -[builtins fixtures/for.py] +[builtins fixtures/for.pyi] [case testErrorInListComprehensionCondition] from typing import List a = None # type: List[A] a = [x for x in a if x()] # E: "A" not callable class A: pass -[builtins fixtures/for.py] +[builtins fixtures/for.pyi] [case testTypeInferenceOfListComprehension] from typing import List a = None # type: List[A] o = [x for x in a] # type: List[object] class A: pass -[builtins fixtures/for.py] +[builtins fixtures/for.pyi] [case testSimpleListComprehensionInClassBody] from typing import List @@ -1138,7 +1138,7 @@ class A: a = [x for x in a] b = [x for x in a] # type: List[B] # E: List comprehension has incompatible type List[A] class B: pass -[builtins fixtures/for.py] +[builtins fixtures/for.pyi] [out] main: note: In class "A": @@ -1154,7 +1154,7 @@ a = {x for x in a} b = {x for x in a} # type: Set[B] # E: Set comprehension has incompatible type Set[A] class A: pass class B: pass -[builtins fixtures/set.py] +[builtins fixtures/set.pyi] -- Dictionary comprehension @@ -1170,7 +1170,7 @@ x = {a: b for a, b in abl} # type: Dict[B, A] y = {a: b for a, b in abl} # type: A class A: pass class B: pass -[builtins fixtures/dict.py] +[builtins fixtures/dict.pyi] [out] main:5: error: Key expression in dictionary comprehension has incompatible type "A"; expected type "B" main:5: error: Value expression in dictionary comprehension has incompatible type "B"; expected type "A" @@ -1186,7 +1186,7 @@ class A: pass class B: pass class C: pass def f(b: A) -> C: pass -[builtins fixtures/dict.py] +[builtins fixtures/dict.pyi] [out] main:4: error: Argument 1 to "f" has incompatible type "B"; expected "A" main:4: error: Value expression in dictionary comprehension has incompatible type "C"; expected type "B" @@ -1204,7 +1204,7 @@ a = None # type: Iterator[int] a = x for x in a b = None # type: Iterator[str] b = x for x in a # E: Generator has incompatible item type "int" -[builtins fixtures/for.py] +[builtins fixtures/for.pyi] -- Conditional expressions @@ -1239,7 +1239,7 @@ import typing x = [1] if None else [] x = [1] x = ['x'] # E: List item 0 has incompatible type "str" -[builtins fixtures/list.py] +[builtins fixtures/list.pyi] -- Special cases @@ -1346,7 +1346,7 @@ class str: pass def f(x: int) -> None: x = yield f('') x = 1 -[builtins fixtures/for.py] +[builtins fixtures/for.pyi] [out] main: note: In function "f": main:1: error: The return type of a generator function should be "Generator" or one of its supertypes @@ -1356,7 +1356,7 @@ main:2: error: Argument 1 to "f" has incompatible type "str"; expected "int" from typing import Iterator def f(x: int) -> Iterator[None]: (yield) -[builtins fixtures/for.py] +[builtins fixtures/for.pyi] [out] @@ -1400,21 +1400,21 @@ d3 = dict(a=1) # type: Dict[int, int] # E: List item 0 has incompatible type "Tu d4 = dict(a=1, b=1) d4.xyz # E: Dict[str, int] has no attribute "xyz" d5 = dict(a=1, b='') # type: Dict[str, Any] -[builtins fixtures/dict.py] +[builtins fixtures/dict.pyi] [case testDictWithoutKeywordArgs] from typing import Dict d = dict() # E: Need type annotation for variable d2 = dict() # type: Dict[int, str] dict(undefined) # E: Name 'undefined' is not defined -[builtins fixtures/dict.py] +[builtins fixtures/dict.pyi] [case testDictFromList] from typing import Dict d = dict([(1, 'x'), (2, 'y')]) d() # E: Dict[int, str] not callable d2 = dict([(1, 'x')]) # type: Dict[str, str] # E: List item 0 has incompatible type "Tuple[int, str]" -[builtins fixtures/dict.py] +[builtins fixtures/dict.pyi] [case testDictFromIterableAndKeywordArg] from typing import Dict @@ -1427,17 +1427,17 @@ d2 = dict(it, x='') # E: Cannot infer type argument 2 of "dict" d2() # E: Dict[Any, Any] not callable d3 = dict(it, x='') # type: Dict[str, int] # E: Argument 2 to "dict" has incompatible type "str"; expected "int" -[builtins fixtures/dict.py] +[builtins fixtures/dict.pyi] [case testDictFromIterableAndKeywordArg2] it = [(1, 'x')] dict(it, x='y') # E: Keyword argument only valid with "str" key type in call to "dict" -[builtins fixtures/dict.py] +[builtins fixtures/dict.pyi] [case testDictFromIterableAndKeywordArg3] d = dict([], x=1) d() # E: Dict[str, int] not callable -[builtins fixtures/dict.py] +[builtins fixtures/dict.pyi] [case testDictFromIterableAndStarStarArgs] from typing import Dict @@ -1452,14 +1452,14 @@ d2 = dict(it, **kw2) # E: Cannot infer type argument 2 of "dict" d2() # E: Dict[Any, Any] not callable d3 = dict(it, **kw2) # type: Dict[str, int] # E: Argument 2 to "dict" has incompatible type **Dict[str, str]; expected "int" -[builtins fixtures/dict.py] +[builtins fixtures/dict.pyi] [case testDictFromIterableAndStarStarArgs2] it = [(1, 'x')] kw = {'x': 'y'} d = dict(it, **kw) # E: Keyword argument only valid with "str" key type in call to "dict" d() # E: Dict[int, str] not callable -[builtins fixtures/dict.py] +[builtins fixtures/dict.pyi] [case testUserDefinedClassNamedDict] from typing import Generic, TypeVar @@ -1468,7 +1468,7 @@ S = TypeVar('S') class dict(Generic[T, S]): def __init__(self, x: T, **kwargs: T) -> None: pass dict(1, y=1) -[builtins fixtures/dict.py] +[builtins fixtures/dict.pyi] [case testSpecialSignatureForSubclassOfDict] from typing import TypeVar, Dict, Generic @@ -1482,14 +1482,14 @@ da() # E: D2[str, int] not callable D2([(1, 2)], x=1) # E: Keyword argument only valid with "str" key type in call to "dict" db = D2(x=1) db() # E: D2[str, int] not callable -[builtins fixtures/dict.py] +[builtins fixtures/dict.pyi] [case testSpecialSignatureForSubclassOfDict2] from typing import TypeVar, Dict, Generic T = TypeVar('T') class D(Dict[str, T], Generic[T]): pass D([('x', 1)], x=1) -[builtins fixtures/dict.py] +[builtins fixtures/dict.pyi] [case testOverridingSpecialSignatureInSubclassOfDict] from typing import TypeVar, Dict, Generic @@ -1499,7 +1499,7 @@ class D(Dict[T, S], Generic[T, S]): def __init__(self, x: S, y: T) -> None: pass d = D(1, y='') d() # E: D[str, int] not callable -[builtins fixtures/dict.py] +[builtins fixtures/dict.pyi] [case testRevealType] reveal_type(1) # E: Revealed type is 'builtins.int' @@ -1520,16 +1520,16 @@ reveal_type = 1 [case testEqNone] None == None -[builtins fixtures/ops.py] +[builtins fixtures/ops.pyi] [case testLtNone] None < None # E: Unsupported left operand type for < (None) -[builtins fixtures/ops.py] +[builtins fixtures/ops.pyi] [case testDictWithStarExpr] # options: fast_parser b = {'z': 26, *a} # E: invalid syntax -[builtins fixtures/dict.py] +[builtins fixtures/dict.pyi] [case testDictWithStarStarExpr] # options: fast_parser @@ -1540,4 +1540,4 @@ c = {**b} d = {**a, **b, 'c': 3} e = {1: 'a', **a} # E: Argument 1 to "update" of "dict" has incompatible type Dict[str, int]; expected Mapping[int, str] f = {**b} # type: Dict[int, int] # E: List item 0 has incompatible type Dict[str, int] -[builtins fixtures/dict.py] +[builtins fixtures/dict.pyi] diff --git a/test-data/unit/check-fastparse.test b/test-data/unit/check-fastparse.test index 7ef5bd34e0ed..3cef2544b619 100644 --- a/test-data/unit/check-fastparse.test +++ b/test-data/unit/check-fastparse.test @@ -31,7 +31,7 @@ class C: def x(self) -> str: pass @x.setter def x(self, value: str) -> None: pass -[builtins fixtures/property.py] +[builtins fixtures/property.pyi] [case testFastParseConditionalProperty] # options: fast_parser @@ -41,7 +41,7 @@ class C: def x(self) -> str: pass @x.setter def x(self, value: str) -> None: pass -[builtins fixtures/property.py] +[builtins fixtures/property.pyi] [case testFastParsePerArgumentAnnotations] # options: fast_parser @@ -64,7 +64,7 @@ def f(a, # type: A reveal_type(d) # E: Revealed type is '__main__.D' reveal_type(e) # E: Revealed type is '__main__.E' reveal_type(kwargs) # E: Revealed type is 'builtins.dict[builtins.str, __main__.F]' -[builtins fixtures/dict.py] +[builtins fixtures/dict.pyi] [out] main: note: In function "f": @@ -91,7 +91,7 @@ def f(a, # type: A reveal_type(e) # E: Revealed type is '__main__.E' reveal_type(kwargs) # E: Revealed type is 'builtins.dict[builtins.str, __main__.F]' return "not an int" # E: Incompatible return value type (got "str", expected "int") -[builtins fixtures/dict.py] +[builtins fixtures/dict.pyi] [out] main: note: In function "f": @@ -102,7 +102,7 @@ def f(*, # type: int # E: bare * has associated type comment ): # type: (...) -> int pass -[builtins fixtures/dict.py] +[builtins fixtures/dict.pyi] [out] [case testFastParsePerArgumentAnnotationsWithReturnAndBareStar] @@ -113,7 +113,7 @@ def f(*, # type: (...) -> int reveal_type(x) # E: Revealed type is 'builtins.str' return "not an int" # E: Incompatible return value type (got "str", expected "int") -[builtins fixtures/dict.py] +[builtins fixtures/dict.pyi] [out] main: note: In function "f": @@ -131,7 +131,7 @@ def f(a, # type: A reveal_type(a) # E: Revealed type is '__main__.A' reveal_type(b) # E: Revealed type is '__main__.B' reveal_type(args) # E: Revealed type is 'builtins.tuple[__main__.C]' -[builtins fixtures/dict.py] +[builtins fixtures/dict.pyi] [out] main: note: In function "f": @@ -151,7 +151,7 @@ def f(a, # type: A reveal_type(b) # E: Revealed type is '__main__.B' reveal_type(args) # E: Revealed type is 'builtins.tuple[__main__.C]' return "not an int" # E: Incompatible return value type (got "str", expected "int") -[builtins fixtures/dict.py] +[builtins fixtures/dict.pyi] [out] main: note: In function "f": diff --git a/test-data/unit/check-functions.test b/test-data/unit/check-functions.test index 9106232841b9..21fc62a9eca0 100644 --- a/test-data/unit/check-functions.test +++ b/test-data/unit/check-functions.test @@ -186,7 +186,7 @@ f([C]) # E: List item 0 has incompatible type class D: def __init__(self, a, b): pass f([D]) # E: List item 0 has incompatible type -[builtins fixtures/list.py] +[builtins fixtures/list.pyi] -- Default argument values -- ----------------------- @@ -715,7 +715,7 @@ class A: def f(self, x): pass def dec(f): return f -[builtins fixtures/staticmethod.py] +[builtins fixtures/staticmethod.pyi] [case testForwardReferenceToStaticallyTypedDecoratedMethod] from typing import TypeVar @@ -730,7 +730,7 @@ class A: T = TypeVar('T') def dec(f: T) -> T: return f -[builtins fixtures/staticmethod.py] +[builtins fixtures/staticmethod.pyi] [out] main: note: In function "f": @@ -741,7 +741,7 @@ def f(self) -> None: class A: @property def x(self): pass -[builtins fixtures/property.py] +[builtins fixtures/property.pyi] [case testForwardReferenceToStaticallyTypedProperty] def f(self) -> None: @@ -750,7 +750,7 @@ def f(self) -> None: class A: @property def x(self) -> int: return 1 -[builtins fixtures/property.py] +[builtins fixtures/property.pyi] [out] main: note: In function "f": @@ -762,7 +762,7 @@ def f(self) -> None: class A: @staticmethod def x(x): pass -[builtins fixtures/staticmethod.py] +[builtins fixtures/staticmethod.pyi] [out] main: note: In function "f": @@ -774,7 +774,7 @@ def f(self) -> None: class A: @staticmethod def x(a: int) -> str: return '' -[builtins fixtures/staticmethod.py] +[builtins fixtures/staticmethod.pyi] [out] main: note: In function "f": @@ -786,7 +786,7 @@ def f(self) -> None: class A: @classmethod def x(cls, a): pass -[builtins fixtures/classmethod.py] +[builtins fixtures/classmethod.pyi] [out] main: note: In function "f": @@ -798,7 +798,7 @@ def f(self) -> None: class A: @classmethod def x(cls, x: int) -> str: return '' -[builtins fixtures/classmethod.py] +[builtins fixtures/classmethod.pyi] [out] main: note: In function "f": @@ -850,7 +850,7 @@ class A: def g(self, x): pass def dec(f): return f -[builtins fixtures/staticmethod.py] +[builtins fixtures/staticmethod.pyi] [case testForwardRefereceToDecoratedFunctionWithCallExpressionDecorator] def f(self) -> None: @@ -1002,6 +1002,20 @@ main:1: note: In module imported here: tmp/a.py:3: error: Argument 1 to "dec" has incompatible type "int"; expected "str" tmp/a.py:5: error: "str" not callable +[case testUndefinedDecoratorInImportCycle] +# cmd: mypy -m foo.base +[file foo/__init__.py] +import foo.base +class Derived(foo.base.Base): + def method(self) -> None: pass +[file foo/base.py] +import foo +class Base: + @decorator + def method(self) -> None: pass +[out] +tmp/foo/base.py:3: error: Name 'decorator' is not defined + -- Conditional function definition -- ------------------------------- @@ -1170,7 +1184,7 @@ if object(): def f(): pass # E: Incompatible redefinition f() f(1) -[builtins fixtures/list.py] +[builtins fixtures/list.pyi] -- Conditional method definition @@ -1280,7 +1294,7 @@ main: note: In function "f": from typing import Callable def f(x: Callable[..., int]) -> None: x(*[1], **{'x': 2}) -[builtins fixtures/dict.py] +[builtins fixtures/dict.pyi] [case testCastWithCallableAndArbitraryArgs] from typing import Callable, cast @@ -1301,7 +1315,7 @@ def f(x: Callable[..., T]) -> T: pass def g(*x: int) -> str: pass x = f(g) x + 1 # E: Unsupported left operand type for + ("str") -[builtins fixtures/list.py] +[builtins fixtures/list.pyi] [case testCallableWithArbitraryArgsSubtyping] from typing import Callable @@ -1333,14 +1347,14 @@ def f(x, y, z): # type: (...) -> None pass f(1, "hello", []) f(x=1, y="hello", z=[]) -[builtins fixtures/dict.py] +[builtins fixtures/dict.pyi] [case testEllipsisWithArbitraryArgsOnBareFunctionWithDefaults] def f(x, y=1, z="hey"): # type: (...) -> None pass f(1, "hello", []) f(x=1, y="hello", z=[]) -[builtins fixtures/dict.py] +[builtins fixtures/dict.pyi] [case testEllipsisWithArbitraryArgsOnBareFunctionWithKwargs] from typing import Dict @@ -1348,7 +1362,7 @@ def f(x, **kwargs): # type: (...) -> None success_dict_type = kwargs # type: Dict[str, str] failure_dict_type = kwargs # type: Dict[int, str] # E: Incompatible types in assignment (expression has type Dict[str, Any], variable has type Dict[int, str]) f(1, thing_in_kwargs=["hey"]) -[builtins fixtures/dict.py] +[builtins fixtures/dict.pyi] [out] main: note: In function "f": @@ -1358,7 +1372,7 @@ def f(x, *args): # type: (...) -> None success_tuple_type = args # type: Tuple[Any, ...] fail_tuple_type = args # type: None # E: Incompatible types in assignment (expression has type Tuple[Any, ...], variable has type None) f(1, "hello") -[builtins fixtures/tuple.py] +[builtins fixtures/tuple.pyi] [out] main: note: In function "f": @@ -1372,14 +1386,14 @@ class A: @classmethod def f(cls, x, y, z): # type: (...) -> None pass -[builtins fixtures/classmethod.py] +[builtins fixtures/classmethod.pyi] [case testEllipsisWithArbitraryArgsOnStaticMethod] class A: @staticmethod def f(x, y, z): # type: (...) -> None pass -[builtins fixtures/staticmethod.py] +[builtins fixtures/staticmethod.pyi] [case testEllipsisWithSomethingAfterItFails] def f(x, y, z): # type: (..., int) -> None @@ -1395,73 +1409,6 @@ def f(x, y, z): # type: (int, ...) -> None main: note: In function "f": main:1: error: Parse error before ): Ellipses cannot accompany other argument types in function type signature. - -[case testDocstringFunction-skip] -def realtypes(x : int, y : int) -> int: - return x - -def f(x, y): - """A function that adds things. - - Args: - x (int): First argument. To be used on all - occasions, even if feeling tired. - y (int): The other argument. Also mandatory, - but less so. - - Returns: - int: The sum. - """ - v = realtypes(x, y) - return v - -[case testDocstringFunctionMismatch-skip] -def realtypes(x : int, y : int) -> str: - return '' - -def f(x, y): - """A function that adds things. - - Args: - x (int): First argument. To be used on all - occasions, even if feeling tired. - y (object): The other argument. Also mandatory, - but less so. - - Returns: - int: The sum. - """ - v = realtypes(x, y) # E: Argument 2 to "realtypes" has incompatible type "object"; expected "int" - return v # E: Incompatible return value type (got "str", expected "int") -[out] -main: note: In function "f": - -[case testCallDocstringFunction-skip] -from typing import List -def f(x): - """ - Args: - x (List[int]): First argument. - Returns: - string - """ - return '' -f([1])() # E: "str" not callable -f(1) # E: Argument 1 to "f" has incompatible type "int"; expected List[int] -[builtins fixtures/list.py] -[out] - -[case testInvalidDocstringAnnotation-skip] -# TODO: Probably should generate an error. -def f(): - """ - Args: - x (foobar/): zar - Returns: - int - """ - return 1 -f() + '' [case testRejectCovariantArgument] from typing import TypeVar, Generic @@ -1469,7 +1416,7 @@ t = TypeVar('t', covariant=True) class A(Generic[t]): def foo(self, x: t) -> None: return None -[builtins fixtures/bool.py] +[builtins fixtures/bool.pyi] [out] main: note: In member "foo" of class "A": main:5: error: Cannot use a covariant type variable as a parameter @@ -1481,7 +1428,7 @@ t = TypeVar('t', contravariant=True) class A(Generic[t]): def foo(self) -> t: return None -[builtins fixtures/bool.py] +[builtins fixtures/bool.pyi] [out] main: note: In member "foo" of class "A": main:5: error: Cannot use a contravariant type variable as return type @@ -1493,7 +1440,7 @@ t = TypeVar('t', covariant=True) class A(Generic[t]): def foo(self) -> t: return None -[builtins fixtures/bool.py] +[builtins fixtures/bool.pyi] [case testAcceptContravariantArgument] from typing import TypeVar, Generic @@ -1501,7 +1448,7 @@ t = TypeVar('t', contravariant=True) class A(Generic[t]): def foo(self, x: t) -> None: return None -[builtins fixtures/bool.py] +[builtins fixtures/bool.pyi] -- Redefining functions @@ -1531,7 +1478,7 @@ else: def g(): pass f() g() -[builtins fixtures/list.py] +[builtins fixtures/list.pyi] [case testFunctionDefinitionWithWhileStatement] while 1: @@ -1551,7 +1498,7 @@ def f1() -> bool: return False foo(f1) -[builtins fixtures/bool.py] +[builtins fixtures/bool.pyi] [case testFunctionNestedWithinWith] from typing import Any diff --git a/test-data/unit/check-generic-subtyping.test b/test-data/unit/check-generic-subtyping.test index e5c4a86352ca..0835995d7a86 100644 --- a/test-data/unit/check-generic-subtyping.test +++ b/test-data/unit/check-generic-subtyping.test @@ -250,7 +250,7 @@ class B(A): def f(self, x: List[S], y: List[T]) -> None: pass class C(A): def f(self, x: List[T], y: List[T]) -> None: pass # E: Signature of "f" incompatible with supertype "A" -[builtins fixtures/list.py] +[builtins fixtures/list.pyi] [out] main: note: In class "C": @@ -349,7 +349,7 @@ class B(Generic[T]): pass class A(B): def f(self, a, b): pass -[builtins fixtures/tuple.py] +[builtins fixtures/tuple.pyi] [out] @@ -697,7 +697,7 @@ class Nums(Iterable[int]): def __next__(self): pass n, n = Nums() s, s = Nums() # E: Incompatible types in assignment (expression has type "int", variable has type "str") -[builtins fixtures/for.py] +[builtins fixtures/for.pyi] [out] diff --git a/test-data/unit/check-generics.test b/test-data/unit/check-generics.test index 452160e9c768..2c699ca61fc8 100644 --- a/test-data/unit/check-generics.test +++ b/test-data/unit/check-generics.test @@ -473,7 +473,7 @@ b2, b2 = list_b # E: Incompatible types in assignment (expression has type "B", a, a = list_a b, b2, b = list_b2 -[builtins fixtures/for.py] +[builtins fixtures/for.pyi] [case testMultipleAssignmentWithListsInInitialization] from typing import List @@ -483,7 +483,7 @@ list_a = [A()] a, b = list_object # type: (A, object) # E: Incompatible types in assignment (expression has type "object", variable has type "A") c, d = list_object # type: (object, A) # E: Incompatible types in assignment (expression has type "object", variable has type "A") e, f = list_a # type: (A, object) -[builtins fixtures/for.py] +[builtins fixtures/for.pyi] [case testMultipleAssignmentWithListAndIndexing] from typing import List @@ -518,7 +518,7 @@ a, b = f(a) # E: Incompatible types in assignment (expression has type "int", b, b = f(a) # E: Incompatible types in assignment (expression has type "int", variable has type "str") a, a = f(a) b, b = f(b) -[builtins fixtures/for.py] +[builtins fixtures/for.pyi] -- Error messages @@ -586,7 +586,7 @@ a = f(b) # E: Incompatible types in assignment (expression has type "B", varia a = f([a]) b = f(b) -[builtins fixtures/list.py] +[builtins fixtures/list.pyi] [case testGenericFunctionAsOverloadItem] from typing import overload, TypeVar, List @@ -608,7 +608,7 @@ a = f(b) # E: Incompatible types in assignment (expression has type "B", varia a = f([a]) b = f([b]) b = f(b) -[builtins fixtures/list.py] +[builtins fixtures/list.pyi] -- Type variable scoping @@ -762,7 +762,7 @@ def f(a: T, b: T) -> T: return a else: return b -[builtins fixtures/ops.py] +[builtins fixtures/ops.pyi] [case testTypeVariableTypeIs] from typing import TypeVar @@ -772,7 +772,7 @@ def f(a: T, b: T) -> T: return a else: return b -[builtins fixtures/ops.py] +[builtins fixtures/ops.pyi] [case testTypeVariableTypeLessThan] from typing import TypeVar @@ -782,7 +782,7 @@ def f(a: T, b: T) -> T: return a else: return b -[builtins fixtures/ops.py] +[builtins fixtures/ops.pyi] [out] main: note: In function "f": main:4: error: Unsupported left operand type for < ("T") @@ -857,3 +857,21 @@ from typing import TypeVar, Container T = TypeVar('T') def f(x: Container[T]) -> T: ... reveal_type(f((1, 2))) # E: Revealed type is 'builtins.int*' + +[case testClassMethodInGenericClassWithGenericConstructorArg] +from typing import TypeVar, Generic +T = TypeVar('T') +class A(Generic[T]): + def __init__(self, a: T) -> None: pass + @classmethod + def f(cls) -> None: pass +[builtins fixtures/classmethod.pyi] + +[case testClassMethodInClassWithGenericConstructor] +from typing import TypeVar, Generic +T = TypeVar('T') +class A: + def __init__(self, a: T) -> None: pass + @classmethod + def f(cls) -> None: pass +[builtins fixtures/classmethod.pyi] diff --git a/test-data/unit/check-ignore.test b/test-data/unit/check-ignore.test index 98c6e05bd363..ecef2e438d3a 100644 --- a/test-data/unit/check-ignore.test +++ b/test-data/unit/check-ignore.test @@ -52,7 +52,7 @@ b.bar() # E: "module" has no attribute "bar" [file b.py] foo = 3 -[builtins fixtures/module_all.py] +[builtins fixtures/module_all.pyi] [out] [case testIgnoreImportStarFromBadModule] @@ -80,26 +80,26 @@ m.x = object # type: ignore m.f() # type: ignore m.y # E: "module" has no attribute "y" [file m.py] -[builtins fixtures/module.py] +[builtins fixtures/module.pyi] [case testIgnoreTypeInferenceError] x = [] # type: ignore y = x x.append(1) -[builtins fixtures/list.py] +[builtins fixtures/list.pyi] [case testIgnoreTypeInferenceError2] def f() -> None: pass x = f() # type: ignore y = x x = 1 -[builtins fixtures/list.py] +[builtins fixtures/list.pyi] [case testIgnoreTypeInferenceErrorAndMultipleAssignment] x, y = [], [] # type: ignore z = x z = y -[builtins fixtures/list.py] +[builtins fixtures/list.pyi] [case testIgnoreSomeStarImportErrors] from m1 import * @@ -147,7 +147,7 @@ class C(m.B): C.f(1) # E: Too many arguments for "f" of "C" C.g(1) C.x = 1 -[builtins fixtures/staticmethod.py] +[builtins fixtures/staticmethod.pyi] [out] [case testIgnoredModuleDefinesBaseClassWithInheritance1] diff --git a/test-data/unit/check-incremental.test b/test-data/unit/check-incremental.test index c45c31812f7c..035c624e0555 100644 --- a/test-data/unit/check-incremental.test +++ b/test-data/unit/check-incremental.test @@ -117,7 +117,7 @@ class Foo: class Bar: def test(self) -> int: return 3 -[builtins fixtures/module_all.py] +[builtins fixtures/module_all.pyi] [stale] [out] @@ -132,7 +132,7 @@ import parent.b [file parent/b.py] -[builtins fixtures/args.py] +[builtins fixtures/args.pyi] [stale] [out] @@ -152,7 +152,7 @@ import parent.a [file parent/c.py] import parent.a -[builtins fixtures/args.py] +[builtins fixtures/args.pyi] [stale] [out] @@ -254,3 +254,93 @@ class MyObject(object): from bar import FooBar [stale] [out] + +[case testIncrementalSameFileSize] +import m + +[file m.py] +def foo(a: int) -> None: pass +def bar(a: str) -> None: pass + +foo(3) + +[file m.py.next] +def foo(a: int) -> None: pass +def bar(a: str) -> None: pass + +bar(3) + +[stale m] +[out] +main:1: note: In module imported here: +tmp/m.py:4: error: Argument 1 to "bar" has incompatible type "int"; expected "str" + +[case testIncrementalUnsilencingModule] +# cmd: mypy -m main package.subpackage.mod2 +# cmd2: mypy -m main package.subpackage.mod1 +# options: silent_imports + +[file main.py] +from package.subpackage.mod1 import Class + +def handle(c: Class) -> None: + c.some_attribute + +[file package/__init__.py] +# empty + +[file package/subpackage/__init__.py] +# empty + +[file package/subpackage/mod1.py] +import collections # Any previously unloaded package works here + +class Class: pass + +[file package/subpackage/mod2.py] +# empty + +[builtins fixtures/args.pyi] +[stale collections, main, package.subpackage.mod1] +[out] +tmp/main.py: note: In function "handle": +tmp/main.py:4: error: "Class" has no attribute "some_attribute" + +[case testIncrementalWithIgnores] +import foo # type: ignore + +[stale] +[out] + +[case testIncrementalWithSilentImportsAndIgnore] +# cmd: mypy -m main b +# cmd2: mypy -m main c c.submodule +# options: silent_imports + +[file main.py] +import a # type: ignore +import b +import c + +a.A().foo() +b.B().foo() +c.C().foo() + +[file b.py] +class B: + def foo(self) -> None: pass + +[file b.py.next] + +[file c/__init__.py] +class C: pass + +[file c/submodule.py] +val = 3 # type: int +val = "foo" + +[builtins fixtures/module_all.pyi] +[stale main, c, c.submodule] +[out] +tmp/c/submodule.py:2: error: Incompatible types in assignment (expression has type "str", variable has type "int") +tmp/main.py:7: error: "C" has no attribute "foo" diff --git a/test-data/unit/check-inference-context.test b/test-data/unit/check-inference-context.test index e75a434c8edb..4f2d08079039 100644 --- a/test-data/unit/check-inference-context.test +++ b/test-data/unit/check-inference-context.test @@ -135,7 +135,7 @@ def g(a: T) -> List[T]: pass class A(Generic[T]): pass class B: pass -[builtins fixtures/for.py] +[builtins fixtures/for.pyi] [out] main: note: In function "h": @@ -163,7 +163,7 @@ def f(a: T) -> 'Tuple[A[T], A[T]]': pass class A(Generic[T]): pass class B: pass -[builtins fixtures/tuple.py] +[builtins fixtures/tuple.pyi] [out] main:8: error: Incompatible types in assignment (expression has type A[B], variable has type A[object]) main:9: error: Incompatible types in assignment (expression has type A[B], variable has type A[object]) @@ -192,7 +192,7 @@ def h(a: S, b: T) -> 'Tuple[A[S], A[S], A[T], A[T]]': pass class A(Generic[T]): pass class B: pass -[builtins fixtures/tuple.py] +[builtins fixtures/tuple.pyi] [out] main:9: error: Incompatible types in assignment (expression has type A[B], variable has type A[object]) main:10: error: Incompatible types in assignment (expression has type A[B], variable has type A[object]) @@ -344,7 +344,7 @@ aa = [] ao = [] class A: pass -[builtins fixtures/list.py] +[builtins fixtures/list.pyi] [case testSingleItemListExpressions] from typing import List @@ -365,7 +365,7 @@ ao = [None] class A: pass class B: pass -[builtins fixtures/list.py] +[builtins fixtures/list.pyi] [case testMultiItemListExpressions] from typing import List @@ -383,7 +383,7 @@ ao = [a, b] class A: pass class B(A): pass -[builtins fixtures/list.py] +[builtins fixtures/list.pyi] [case testLocalVariableInferenceFromEmptyList] import typing @@ -394,7 +394,7 @@ def f() -> None: c = [object()] # E: List item 0 has incompatible type "object" c = [B()] class B: pass -[builtins fixtures/list.py] +[builtins fixtures/list.pyi] [out] main: note: In function "f": @@ -414,7 +414,7 @@ aab = [[None], [b], []] aab = [ab, []] class B: pass -[builtins fixtures/list.py] +[builtins fixtures/list.pyi] -- Complex context @@ -425,7 +425,7 @@ class B: pass from typing import List l = ([A()]) # type: List[object] class A: pass -[builtins fixtures/list.py] +[builtins fixtures/list.pyi] [case testComplexTypeInferenceWithTuple] from typing import TypeVar, Tuple, Generic @@ -440,7 +440,7 @@ class A(Generic[t]): pass class B: pass class C: pass class D(Generic[k, v]): pass -[builtins fixtures/list.py] +[builtins fixtures/list.pyi] -- Dictionary literals @@ -457,7 +457,7 @@ a_b = A() # type: A[B] a_c = A() # type: A[C] d = {A() : a_c, a_b : A()} # type: Dict[A[B], A[C]] -[builtins fixtures/dict.py] +[builtins fixtures/dict.pyi] -- Special cases (regression tests etc.) @@ -534,7 +534,7 @@ class set(Generic[t]): b = bool() l = set([b]) l = set([object()]) # E: List item 0 has incompatible type "object" -[builtins fixtures/for.py] +[builtins fixtures/for.pyi] -- Infer generic type in 'Any' context @@ -548,7 +548,7 @@ t = TypeVar('t') x = [] # type: Any y = C() # type: Any class C(Generic[s, t]): pass -[builtins fixtures/list.py] +[builtins fixtures/list.pyi] -- Lambdas @@ -571,7 +571,7 @@ f = lambda: [] f = lambda: [B()] # E: List item 0 has incompatible type "B" class A: pass class B: pass -[builtins fixtures/list.py] +[builtins fixtures/list.pyi] [case testInferLambdaAsGenericFunctionArgument] from typing import TypeVar, List, Any, Callable @@ -581,7 +581,7 @@ class A: def f(a: List[t], fn: Callable[[t], Any]) -> None: pass list_a = [] # type: List[A] f(list_a, lambda a: a.x) -[builtins fixtures/list.py] +[builtins fixtures/list.pyi] [case testInvalidContextForLambda] from typing import Callable @@ -600,7 +600,7 @@ f2 = lambda: 1 # type: Callable[..., int] f3 = lambda *args, **kwargs: 1 # type: Callable[..., int] f4 = lambda x: x # type: Callable[..., int] g = lambda x: 1 # type: Callable[..., str] -[builtins fixtures/dict.py] +[builtins fixtures/dict.pyi] [out] main:6: error: Incompatible return value type (got "int", expected "str") main:6: error: Incompatible types in assignment (expression has type Callable[[Any], int], variable has type Callable[..., str]) @@ -632,7 +632,7 @@ f(lambda x: x if isinstance(x, B) else B(), A(), r=B())() # E: "B" not callable f( # E: Argument 1 to "f" has incompatible type Callable[[A], A]; expected Callable[[A], B] lambda x: B() if isinstance(x, B) else x, # E: Incompatible return value type (got "A", expected "B") A(), r=B()) -[builtins fixtures/isinstance.py] +[builtins fixtures/isinstance.pyi] -- Overloads + generic functions @@ -656,7 +656,7 @@ class B: pass m = map(g, [A()]) b = m # type: List[B] a = m # type: List[A] # E: Incompatible types in assignment (expression has type List[B], variable has type List[A]) -[builtins fixtures/list.py] +[builtins fixtures/list.pyi] -- Boolean operators @@ -675,7 +675,7 @@ b = b or c # E: Incompatible types in assignment (expression has type "Union[Lis class A: pass class B: pass class C(B): pass -[builtins fixtures/list.py] +[builtins fixtures/list.pyi] -- Special cases @@ -693,7 +693,7 @@ a = f(B(), B()) # E: Argument 1 to "f" has incompatible type "B"; expected "A" def f(a: s, b: t) -> List[s]: pass class A: pass class B: pass -[builtins fixtures/list.py] +[builtins fixtures/list.pyi] [case testSomeTypeVarsInferredFromContext2] from typing import List, TypeVar @@ -706,7 +706,7 @@ a = f(B(), B()) # E: Argument 1 to "f" has incompatible type "B"; expected "A" def f(a: s, b: t) -> List[s]: pass class A: pass class B: pass -[builtins fixtures/list.py] +[builtins fixtures/list.pyi] [case testLambdaInListAndHigherOrderFunction] from typing import TypeVar, Callable, List @@ -716,7 +716,7 @@ map( [lambda x: x], []) def map(f: List[Callable[[t], s]], a: List[t]) -> List[s]: pass class A: pass -[builtins fixtures/list.py] +[builtins fixtures/list.pyi] [out] [case testChainedAssignmentInferenceContexts] @@ -725,7 +725,7 @@ i = None # type: List[int] s = None # type: List[str] i = i = [] i = s = [] # E: Incompatible types in assignment (expression has type List[str], variable has type List[int]) -[builtins fixtures/list.py] +[builtins fixtures/list.pyi] [case testContextForAttributeDeclaredInInit] from typing import List @@ -736,14 +736,14 @@ a = A() a.x = [] a.x = [1] a.x = [''] # E: List item 0 has incompatible type "str" -[builtins fixtures/list.py] +[builtins fixtures/list.pyi] [case testListMultiplyInContext] from typing import List a = None # type: List[int] a = [None] * 3 a = [''] * 3 # E: List item 0 has incompatible type "str" -[builtins fixtures/list.py] +[builtins fixtures/list.pyi] [case testUnionTypeContext] from typing import Union, List, TypeVar @@ -752,7 +752,7 @@ def f(x: Union[List[T], str]) -> None: pass f([1]) f('') f(1) # E: Argument 1 to "f" has incompatible type "int"; expected "Union[List[None], str]" -[builtins fixtures/isinstancelist.py] +[builtins fixtures/isinstancelist.pyi] [case testIgnoringInferenceContext] from typing import TypeVar, List @@ -761,7 +761,7 @@ def f(x: List[T]) -> T: pass def g(y: object) -> None: pass a = [1] g(f(a)) -[builtins fixtures/list.py] +[builtins fixtures/list.pyi] [case testStar2Context] from typing import Any, Dict, Tuple, Iterable @@ -769,7 +769,7 @@ def f1(iterable: Iterable[Tuple[str, Any]] = None) -> None: f2(**dict(iterable)) def f2(iterable: Iterable[Tuple[str, Any]], **kw: Any) -> None: pass -[builtins fixtures/dict.py] +[builtins fixtures/dict.pyi] [out] [case testInferenceInGenericFunction] @@ -779,7 +779,7 @@ def f(a: T) -> None: l = [] # type: List[T] l.append(a) l.append(1) # E: Argument 1 to "append" of "list" has incompatible type "int"; expected "T" -[builtins fixtures/list.py] +[builtins fixtures/list.pyi] [out] main: note: In function "f": @@ -792,7 +792,7 @@ class A(Generic[S]): l = [] # type: List[T] l.append(a) l.append(b) # E: Argument 1 to "append" of "list" has incompatible type "S"; expected "T" -[builtins fixtures/list.py] +[builtins fixtures/list.pyi] [out] main: note: In member "f" of class "A": diff --git a/test-data/unit/check-inference.test b/test-data/unit/check-inference.test index dc40b650dff8..953e68add374 100644 --- a/test-data/unit/check-inference.test +++ b/test-data/unit/check-inference.test @@ -109,7 +109,7 @@ def f() -> None: class A: pass class B: pass -[builtins fixtures/tuple.py] +[builtins fixtures/tuple.pyi] [out] main: note: In function "f": @@ -120,7 +120,7 @@ def f() -> None: b = None, A() # E: Need type annotation for variable class A: pass -[builtins fixtures/tuple.py] +[builtins fixtures/tuple.pyi] [out] main: note: In function "f": @@ -136,7 +136,7 @@ def f() -> None: a = a_int a = a_s # E: Incompatible types in assignment (expression has type A[str], variable has type A[int]) a = a_i -[builtins fixtures/tuple.py] +[builtins fixtures/tuple.pyi] [out] main: note: In function "f": @@ -286,7 +286,7 @@ def f() -> None: a, b = t # Fail c, d, e, f = t # Fail g, h, i = t -[builtins fixtures/tuple.py] +[builtins fixtures/tuple.pyi] [out] main: note: In function "f": main:5: error: Too many values to unpack (2 expected, 3 provided) @@ -298,7 +298,7 @@ def f() -> None: a, b = f # E: 'def ()' object is not iterable c, d = A() # E: '__main__.A' object is not iterable class A: pass -[builtins fixtures/for.py] +[builtins fixtures/for.pyi] [out] main: note: In function "f": @@ -308,7 +308,7 @@ def f() -> None: a1, (a2, b) = A(), f # E: 'def ()' object is not iterable a3, (c, d) = A(), A() # E: '__main__.A' object is not iterable class A: pass -[builtins fixtures/for.py] +[builtins fixtures/for.pyi] [out] main: note: In function "f": @@ -337,7 +337,7 @@ def f() -> None: a = b c = d d = e -[builtins fixtures/for.py] +[builtins fixtures/for.pyi] [out] main: note: In function "f": @@ -366,7 +366,7 @@ def f() -> None: a = b c = d d = e -[builtins fixtures/for.py] +[builtins fixtures/for.pyi] [out] main: note: In function "f": @@ -394,7 +394,7 @@ a, b = Nums() a = b = 1 a = '' # E: Incompatible types in assignment (expression has type "str", variable has type "int") b = '' # E: Incompatible types in assignment (expression has type "str", variable has type "int") -[builtins fixtures/for.py] +[builtins fixtures/for.pyi] -- Type variable inference for generic functions @@ -420,7 +420,7 @@ def id(a: T) -> T: pass class A: pass class B: pass -[builtins fixtures/tuple.py] +[builtins fixtures/tuple.pyi] [case testInferringGenericFunctionTypeForLvar] from typing import TypeVar @@ -504,7 +504,7 @@ def f(a: T, b: S) -> Tuple[T, S]: pass class A: pass class B: pass -[builtins fixtures/tuple.py] +[builtins fixtures/tuple.pyi] [out] main:9: error: Argument 2 to "f" has incompatible type "B"; expected "A" main:10: error: Argument 1 to "f" has incompatible type "B"; expected "A" @@ -687,7 +687,7 @@ l = mymap(f, [b]) l = [A()] lb = [b] l = lb # E: Incompatible types in assignment (expression has type List[bool], variable has type List[A]) -[builtins fixtures/for.py] +[builtins fixtures/for.pyi] -- Generic function inference with unions @@ -724,7 +724,7 @@ b = ['b'] i(a, a, b) i(b, a, b) i(a, b, b) # E: Argument 1 to "i" has incompatible type List[int]; expected List[str] -[builtins fixtures/list.py] +[builtins fixtures/list.pyi] [case testUnionInferenceWithTypeVarValues] @@ -737,7 +737,7 @@ f('foo', b'bar') # E: Type argument 1 of "f" has incompatible value "object" f(1) f(1, 'foo') f(1, 'foo', b'bar') # E: Type argument 1 of "f" has incompatible value "object" -[builtins fixtures/primitives.py] +[builtins fixtures/primitives.pyi] [case testUnionTwoPassInference-skip] @@ -753,7 +753,7 @@ b = ['b'] # not a subtype of List[str], we must have U = int. # This is not currently implemented. j(a, b) -[builtins fixtures/list.py] +[builtins fixtures/list.pyi] [case testUnionContext] @@ -764,7 +764,7 @@ d1 = f() # type: Union[List[int], str] d2 = f() # type: Union[int, str] # E: Incompatible types in assignment (expression has type List[None], variable has type "Union[int, str]") def g(x: T) -> List[T]: pass d3 = g(1) # type: Union[List[int], List[str]] -[builtins fixtures/list.py] +[builtins fixtures/list.pyi] [case testGenericFunctionSubtypingWithUnions] @@ -779,7 +779,7 @@ a = k1 # E: Incompatible types in assignment (expression has type Callable[[int, b = k1 b = k1 b = k2 -[builtins fixtures/list.py] +[builtins fixtures/list.pyi] -- Literal expressions @@ -796,7 +796,7 @@ a, b = None, None # type: (A, B) d = {a:b} d = d_ab() d = d_aa() # E: Incompatible types in assignment (expression has type Dict[A, A], variable has type Dict[A, B]) -[builtins fixtures/dict.py] +[builtins fixtures/dict.pyi] [case testSetLiteral] from typing import Any, Set @@ -807,7 +807,7 @@ s = {a} s = {x} s = s_i() s = s_s() # E: Incompatible types in assignment (expression has type Set[str], variable has type Set[int]) -[builtins fixtures/set.py] +[builtins fixtures/set.pyi] [case testSetWithStarExpr] # options: fast_parser @@ -815,7 +815,7 @@ s = {1, 2, *(3, 4)} t = {1, 2, *s} reveal_type(s) # E: Revealed type is 'builtins.set[builtins.int*]' reveal_type(t) # E: Revealed type is 'builtins.set[builtins.int*]' -[builtins fixtures/set.py] +[builtins fixtures/set.pyi] -- For statements @@ -834,7 +834,7 @@ for y in []: # E: Need type annotation for variable class A: pass class B: pass -[builtins fixtures/for.py] +[builtins fixtures/for.pyi] [case testInferenceOfFor2] @@ -856,7 +856,7 @@ for xxx, yyy in [(None, None)]: # Fail class A: pass class B: pass class C: pass -[builtins fixtures/for.py] +[builtins fixtures/for.pyi] [out] main:4: error: Incompatible types in assignment (expression has type "A", variable has type "B") main:5: error: Incompatible types in assignment (expression has type "B", variable has type "C") @@ -880,14 +880,14 @@ for e, f in [[]]: # E: Need type annotation for variable class A: pass class B: pass -[builtins fixtures/for.py] +[builtins fixtures/for.pyi] [case testForStatementInferenceWithVoid] import typing for x in f(): # E: "f" does not return a value pass def f() -> None: pass -[builtins fixtures/for.py] +[builtins fixtures/for.pyi] [case testReusingInferredForIndex] import typing @@ -899,7 +899,7 @@ a = A() a = B() # E: Incompatible types in assignment (expression has type "B", variable has type "A") class A: pass class B: pass -[builtins fixtures/for.py] +[builtins fixtures/for.pyi] [case testReusingInferredForIndex2] import typing @@ -912,7 +912,7 @@ def f() -> None: a = B() # E: Incompatible types in assignment (expression has type "B", variable has type "A") class A: pass class B: pass -[builtins fixtures/for.py] +[builtins fixtures/for.pyi] [out] main: note: In function "f": @@ -940,7 +940,7 @@ a = x x = object() # E: Incompatible types in assignment (expression has type "object", variable has type "A") a = object() # E: Incompatible types in assignment (expression has type "object", variable has type "A") class A: pass -[builtins fixtures/for.py] +[builtins fixtures/for.pyi] [case testMultipleAssignmentWithPartialDefinition3] from typing import Any @@ -1022,7 +1022,7 @@ li = [1] l = lambda: li f1 = l # type: Callable[[], List[int]] f2 = l # type: Callable[[], List[str]] # E: Incompatible types in assignment (expression has type Callable[[], List[int]], variable has type Callable[[], List[str]]) -[builtins fixtures/list.py] +[builtins fixtures/list.pyi] [case testInferLambdaType2] from typing import List, Callable @@ -1032,7 +1032,7 @@ f2 = l # type: Callable[[], List[A]] # E: Incompatible types in assignment (expr class A: pass class B: pass -[builtins fixtures/list.py] +[builtins fixtures/list.pyi] [case testUninferableLambda] from typing import TypeVar, Callable @@ -1073,7 +1073,7 @@ a2 = a or [] a = a2 a2 = o # E: Incompatible types in assignment (expression has type List[object], variable has type List[A]) class A: pass -[builtins fixtures/list.py] +[builtins fixtures/list.pyi] -- Accessing variable before its type has been inferred @@ -1112,7 +1112,7 @@ x3 = [B(), B()] a = x1 a = x2 a = x3 # E: Incompatible types in assignment (expression has type List[B], variable has type List[A]) -[builtins fixtures/list.py] +[builtins fixtures/list.pyi] [case testListWithDucktypeCompatibilityAndTransitivity] from typing import List, _promote @@ -1128,7 +1128,7 @@ x3 = [B(), C()] a = x1 a = x2 a = x3 # E: Incompatible types in assignment (expression has type List[B], variable has type List[A]) -[builtins fixtures/list.py] +[builtins fixtures/list.pyi] -- Inferring type of variable when initialized to an empty collection @@ -1139,19 +1139,19 @@ a = x3 # E: Incompatible types in assignment (expression has type List[B], varia a = [] a.append(1) a.append('') # E: Argument 1 to "append" of "list" has incompatible type "str"; expected "int" -[builtins fixtures/list.py] +[builtins fixtures/list.pyi] [out] [case testInferListInitializedToEmptyUsingUpdate] a = [] a.extend(['']) a.append(0) # E: Argument 1 to "append" of "list" has incompatible type "int"; expected "str" -[builtins fixtures/list.py] +[builtins fixtures/list.pyi] [out] [case testInferListInitializedToEmptyAndNotAnnotated] a = [] # E: Need type annotation for variable -[builtins fixtures/list.py] +[builtins fixtures/list.pyi] [out] [case testInferListInitializedToEmptyAndReadBeforeAppend] @@ -1159,14 +1159,14 @@ a = [] # E: Need type annotation for variable if a: pass a.xyz a.append('') -[builtins fixtures/list.py] +[builtins fixtures/list.pyi] [out] [case testInferListInitializedToEmptyAndIncompleteTypeInAppend] a = [] # E: Need type annotation for variable a.append([]) a() -[builtins fixtures/list.py] +[builtins fixtures/list.pyi] [out] [case testInferListInitializedToEmptyAndMultipleAssignment] @@ -1175,7 +1175,7 @@ a.append(1) b.append('') a() # E: List[int] not callable b() # E: List[str] not callable -[builtins fixtures/list.py] +[builtins fixtures/list.pyi] [out] [case testInferListInitializedToEmptyInFunction] @@ -1183,7 +1183,7 @@ def f() -> None: a = [] a.append(1) a.append('') # E: Argument 1 to "append" of "list" has incompatible type "str"; expected "int" -[builtins fixtures/list.py] +[builtins fixtures/list.pyi] [out] main: note: In function "f": @@ -1195,7 +1195,7 @@ def g() -> None: pass a = [] a.append(1) -[builtins fixtures/list.py] +[builtins fixtures/list.pyi] [out] main: note: In function "f": @@ -1205,7 +1205,7 @@ def f() -> None: if a: pass a.xyz a.append('') -[builtins fixtures/list.py] +[builtins fixtures/list.pyi] [out] main: note: In function "f": @@ -1214,7 +1214,7 @@ class A: a = [] a.append(1) a.append('') # E: Argument 1 to "append" of "list" has incompatible type "str"; expected "int" -[builtins fixtures/list.py] +[builtins fixtures/list.pyi] [out] main: note: In class "A": @@ -1225,7 +1225,7 @@ class A: class B: a = [] a.append(1) -[builtins fixtures/list.py] +[builtins fixtures/list.pyi] [out] main: note: In class "A": @@ -1235,7 +1235,7 @@ class A: a = [] a.append(1) a.append('') # E: Argument 1 to "append" of "list" has incompatible type "str"; expected "int" -[builtins fixtures/list.py] +[builtins fixtures/list.pyi] [out] main: note: In member "f" of class "A": @@ -1243,7 +1243,7 @@ main: note: In member "f" of class "A": class A: def f(self) -> None: a = [] # E: Need type annotation for variable -[builtins fixtures/list.py] +[builtins fixtures/list.pyi] [out] main: note: In member "f" of class "A": @@ -1254,7 +1254,7 @@ class A: self.a = [] # E: Need type annotation for variable self.a.append(1) # E: Cannot determine type of 'a' self.a.append('') # E: Cannot determine type of 'a' -[builtins fixtures/list.py] +[builtins fixtures/list.pyi] [out] main: note: In member "f" of class "A": @@ -1262,42 +1262,42 @@ main: note: In member "f" of class "A": a = set() a.add(1) a.add('') # E: Argument 1 to "add" of "set" has incompatible type "str"; expected "int" -[builtins fixtures/set.py] +[builtins fixtures/set.pyi] [out] [case testInferSetInitializedToEmptyUsingDiscard] a = set() a.discard('') a.add(0) # E: Argument 1 to "add" of "set" has incompatible type "int"; expected "str" -[builtins fixtures/set.py] +[builtins fixtures/set.pyi] [out] [case testInferSetInitializedToEmptyUsingUpdate] a = set() a.update({0}) a.add('') # E: Argument 1 to "add" of "set" has incompatible type "str"; expected "int" -[builtins fixtures/set.py] +[builtins fixtures/set.pyi] [out] [case testInferDictInitializedToEmpty] a = {} a[1] = '' a() # E: Dict[int, str] not callable -[builtins fixtures/dict.py] +[builtins fixtures/dict.pyi] [out] [case testInferDictInitializedToEmptyUsingUpdate] a = {} a.update({'': 42}) a() # E: Dict[str, int] not callable -[builtins fixtures/dict.py] +[builtins fixtures/dict.pyi] [out] [case testInferDictInitializedToEmptyUsingUpdateError] a = {} # E: Need type annotation for variable a.update([1, 2]) a() -[builtins fixtures/dict.py] +[builtins fixtures/dict.pyi] [out] [case testInferDictInitializedToEmptyAndIncompleteTypeInUpdate] @@ -1305,21 +1305,21 @@ a = {} # E: Need type annotation for variable a[1] = {} b = {} # E: Need type annotation for variable b[{}] = 1 -[builtins fixtures/dict.py] +[builtins fixtures/dict.pyi] [out] [case testInferDictInitializedToEmptyAndUpdatedFromMethod] map = {} def add(): map[1] = 2 -[builtins fixtures/dict.py] +[builtins fixtures/dict.pyi] [out] [case testSpecialCaseEmptyListInitialization] def f(blocks: Any): # E: Name 'Any' is not defined to_process = [] # E: Need type annotation for variable to_process = list(blocks) -[builtins fixtures/list.py] +[builtins fixtures/list.pyi] [out] main: note: In function "f": @@ -1327,7 +1327,7 @@ main: note: In function "f": def f(blocks: object): to_process = [] # E: Need type annotation for variable to_process = list(blocks) # E: No overload variant of "list" matches argument types [builtins.object] -[builtins fixtures/list.py] +[builtins fixtures/list.pyi] [out] main: note: In function "f": @@ -1379,7 +1379,7 @@ if object(): x = [] x.append(1) x.append('') # E: Argument 1 to "append" of "list" has incompatible type "str"; expected "int" -[builtins fixtures/list.py] +[builtins fixtures/list.pyi] [case testPartiallyInitializedToNoneAndThenReadPartialList] x = None @@ -1387,7 +1387,7 @@ if object(): # Promote from partial None to partial list. x = [] # E: Need type annotation for variable x -[builtins fixtures/list.py] +[builtins fixtures/list.pyi] [case testPartiallyInitializedToNoneAndPartialListAndLeftPartial] def f() -> None: @@ -1395,7 +1395,7 @@ def f() -> None: if object(): # Promote from partial None to partial list. x = [] # E: Need type annotation for variable -[builtins fixtures/list.py] +[builtins fixtures/list.pyi] [out] main: note: In function "f": @@ -1406,7 +1406,7 @@ def f(*x: T) -> Dict[int, T]: pass x = None # E: Need type annotation for variable if object(): x = f() -[builtins fixtures/dict.py] +[builtins fixtures/dict.pyi] [case testPartiallyInitializedVariableDoesNotEscapeScope1] def f() -> None: @@ -1470,7 +1470,7 @@ class A: def f(self) -> None: for a in self.x: pass -[builtins fixtures/for.py] +[builtins fixtures/for.pyi] [out] main: note: In class "A": main:3: error: Need type annotation for variable @@ -1484,7 +1484,7 @@ class A: def f(self) -> None: for a in self.x: pass -[builtins fixtures/for.py] +[builtins fixtures/for.pyi] [out] main: note: In member "f" of class "A": main:3: error: Need type annotation for variable @@ -1497,7 +1497,7 @@ class A: def f(self) -> None: for a in A.x: pass -[builtins fixtures/for.py] +[builtins fixtures/for.pyi] [out] main: note: In class "A": main:2: error: Need type annotation for variable @@ -1591,7 +1591,7 @@ def f() -> None: x.append('') # E: Argument 1 to "append" of "list" has incompatible type "str"; expected "int" x.append(y) # E: Argument 1 to "append" of "list" has incompatible type "str"; expected "int" y = '' -[builtins fixtures/list.py] +[builtins fixtures/list.pyi] [out] main: note: In function "f": @@ -1606,7 +1606,7 @@ def f() -> None: n = x[0] # E: Incompatible types in assignment (expression has type "str", variable has type "int") x.append(1) # E: Argument 1 to "append" of "list" has incompatible type "int"; expected "str" y = '' -[builtins fixtures/list.py] +[builtins fixtures/list.pyi] [out] main: note: In function "f": @@ -1620,7 +1620,7 @@ def f() -> None: x[1] = 1 # E: Incompatible types in assignment (expression has type "int", target has type "str") x[1] = '' y = '' -[builtins fixtures/dict.py] +[builtins fixtures/dict.pyi] [out] main: note: In function "f": @@ -1633,7 +1633,7 @@ def f() -> None: x[1] = 1 g(x) # E: Argument 1 to "g" has incompatible type Dict[int, int]; expected Dict[str, int] y = '' -[builtins fixtures/dict.py] +[builtins fixtures/dict.pyi] [out] main: note: In function "f": @@ -1654,7 +1654,7 @@ def f() -> None: x.append(y) x() # E: List[int] not callable o = 1 -[builtins fixtures/list.py] +[builtins fixtures/list.pyi] [out] main: note: In function "f": @@ -1665,7 +1665,7 @@ def f() -> None: x[''] = y x() # E: Dict[str, int] not callable o = 1 -[builtins fixtures/dict.py] +[builtins fixtures/dict.pyi] [out] main: note: In function "f": @@ -1675,7 +1675,7 @@ def f() -> None: y = o z = {} # E: Need type annotation for variable o = 1 -[builtins fixtures/dict.py] +[builtins fixtures/dict.pyi] [out] main: note: In function "f": @@ -1773,20 +1773,20 @@ a2.foo2() def f(): pass a = [] if f() else [0] a() # E: List[int] not callable -[builtins fixtures/list.py] +[builtins fixtures/list.pyi] [case testUnificationEmptyListRight] def f(): pass a = [0] if f() else [] a() # E: List[int] not callable -[builtins fixtures/list.py] +[builtins fixtures/list.pyi] [case testUnificationEmptyListLeftInContext] from typing import List def f(): pass a = [] if f() else [0] # type: List[int] a() # E: List[int] not callable -[builtins fixtures/list.py] +[builtins fixtures/list.pyi] [case testUnificationEmptyListRightInContext] # TODO Find an example that really needs the context @@ -1794,37 +1794,37 @@ from typing import List def f(): pass a = [0] if f() else [] # type: List[int] a() # E: List[int] not callable -[builtins fixtures/list.py] +[builtins fixtures/list.pyi] [case testUnificationEmptySetLeft] def f(): pass a = set() if f() else {0} a() # E: Set[int] not callable -[builtins fixtures/set.py] +[builtins fixtures/set.pyi] [case testUnificationEmptyDictLeft] def f(): pass a = {} if f() else {0: 0} a() # E: Dict[int, int] not callable -[builtins fixtures/dict.py] +[builtins fixtures/dict.pyi] [case testUnificationEmptyDictRight] def f(): pass a = {0: 0} if f() else {} a() # E: Dict[int, int] not callable -[builtins fixtures/dict.py] +[builtins fixtures/dict.pyi] [case testUnificationDictWithEmptyListLeft] def f(): pass a = {0: []} if f() else {0: [0]} a() # E: Dict[int, List[int]] not callable -[builtins fixtures/dict.py] +[builtins fixtures/dict.pyi] [case testUnificationDictWithEmptyListRight] def f(): pass a = {0: [0]} if f() else {0: []} a() # E: Dict[int, List[int]] not callable -[builtins fixtures/dict.py] +[builtins fixtures/dict.pyi] [case testMisguidedSetItem] from typing import Generic, Sequence, TypeVar diff --git a/test-data/unit/check-isinstance.test b/test-data/unit/check-isinstance.test index 26736b2f92a1..8dab0aa9116a 100644 --- a/test-data/unit/check-isinstance.test +++ b/test-data/unit/check-isinstance.test @@ -18,7 +18,7 @@ else: x = bar() x * 2 -[builtins fixtures/list.py] +[builtins fixtures/list.pyi] [case testGeneratorExpressionTypes] @@ -29,7 +29,7 @@ y = [x] z = [1,2] z = [a.y for b in y for a in b] -[builtins fixtures/list.py] +[builtins fixtures/list.pyi] [case testClassAttributeInitialization-skip] class A: @@ -53,7 +53,7 @@ def foo(x: Union[str, int]): x = None # type: int y = [x] -[builtins fixtures/isinstancelist.py] +[builtins fixtures/isinstancelist.pyi] [out] main: note: In function "foo": @@ -66,7 +66,7 @@ x = A() def foo(x: A = B()): x.y # E: "A" has no attribute "y" -[builtins fixtures/isinstance.py] +[builtins fixtures/isinstance.pyi] [out] main: note: In function "foo": @@ -87,7 +87,7 @@ while isinstance(x, B): x.y x = B() -[builtins fixtures/isinstance.py] +[builtins fixtures/isinstance.pyi] [case testSubtypingWithAny] @@ -120,7 +120,7 @@ x = 1 (x, y) = ('a', 1) x + 1 # E: Unsupported operand types for + ("str" and "int") -[builtins fixtures/isinstancelist.py] +[builtins fixtures/isinstancelist.pyi] [case testUnionIfZigzag] from typing import Union @@ -131,7 +131,7 @@ def f(x: Union[int, str]) -> None: x = 'a' x = 1 x + 1 -[builtins fixtures/isinstancelist.py] +[builtins fixtures/isinstancelist.pyi] [case testTwoLoopsUnion] @@ -152,7 +152,7 @@ def bar() -> None: x = 'a' x + 'a' -[builtins fixtures/isinstancelist.py] +[builtins fixtures/isinstancelist.pyi] [case testComplicatedBlocks] from typing import Union @@ -185,7 +185,7 @@ def bar() -> None: x = 'a' x = 'a' x + 'a' -[builtins fixtures/isinstancelist.py] +[builtins fixtures/isinstancelist.pyi] [out] main: note: In function "bar": @@ -262,7 +262,7 @@ try: except: x = A() x.z # E: "A" has no attribute "z" -[builtins fixtures/exception.py] +[builtins fixtures/exception.pyi] [case testUnionTryExcept4] class A: pass @@ -278,7 +278,7 @@ while 1: else: x = B() x.z -[builtins fixtures/exception.py] +[builtins fixtures/exception.pyi] [case testUnionTryFinally] class A: pass class B(A): b = 1 @@ -337,7 +337,7 @@ while 2: if not isinstance(x, B): break x.b -[builtins fixtures/isinstancelist.py] +[builtins fixtures/isinstancelist.pyi] [case testUnionTryFinally5] class A: pass class B(A): b = 1 @@ -377,7 +377,7 @@ def f(x: Union[List[int], List[str], int]) -> None: x + 1 x[0] # E: Value of type "int" is not indexable x + 1 # E: Unsupported operand types for + (likely involving Union) -[builtins fixtures/isinstancelist.py] +[builtins fixtures/isinstancelist.pyi] [out] main: note: In function "f": @@ -397,7 +397,7 @@ def f(x: Union[A, B, C]) -> None: else: x = g(x) x.a -[builtins fixtures/isinstancelist.py] +[builtins fixtures/isinstancelist.pyi] [case testUnionStrictDefnBasic] from typing import Union @@ -414,7 +414,7 @@ if isinstance(x, str): x = 1 x = x + 1 -[builtins fixtures/isinstancelist.py] +[builtins fixtures/isinstancelist.pyi] [case testSubtypeRedefinitionBasic] from typing import Union @@ -427,7 +427,7 @@ x.y # E: "A" has no attribute "y" x = B() x.y # OK: x is known to be a B -[builtins fixtures/isinstancelist.py] +[builtins fixtures/isinstancelist.pyi] [case testIsInstanceBasic] from typing import Union @@ -440,7 +440,7 @@ if isinstance(x, str): else: x = x + 'a' # E: Unsupported operand types for + ("int" and "str") x = x + 1 -[builtins fixtures/isinstancelist.py] +[builtins fixtures/isinstancelist.pyi] [case testIsInstanceIndexing] from typing import Union @@ -454,7 +454,7 @@ if isinstance(j[0], str): else: j[0] = j[0] + 'a' # E: Unsupported operand types for + ("int" and "str") j[0] = j[0] + 1 -[builtins fixtures/isinstancelist.py] +[builtins fixtures/isinstancelist.pyi] [case testIsInstanceSubClassMember] from typing import Union @@ -484,7 +484,7 @@ while 1: break y = h.pet.paws + 1 z = h.pet.paws + 'a' # E: Unsupported operand types for + ("int" and "str") -[builtins fixtures/isinstancelist.py] +[builtins fixtures/isinstancelist.pyi] [case testIsInstanceSubClassReset] class A: pass class B(A): b=1 @@ -498,7 +498,7 @@ if isinstance(x.a, B): x.a.b x = C() x.a.b # E: "A" has no attribute "b" -[builtins fixtures/isinstance.py] +[builtins fixtures/isinstance.pyi] [case testIsinstanceTuple] from typing import Union @@ -521,7 +521,7 @@ v = A() # type: Union[A, B, C] if isinstance(v, (B, C)): v.method2(123) v.method3('xyz') # E: Some element of union has no attribute "method3" -[builtins fixtures/isinstance.py] +[builtins fixtures/isinstance.pyi] [case testMemberAssignmentChanges-skip] from typing import Union @@ -537,7 +537,7 @@ pet.paws + 'a' pet.paws = 1 pet.paws + 1 -[builtins fixtures/isinstancelist.py] +[builtins fixtures/isinstancelist.pyi] [case testIsInstanceSubClassMemberHard-skip] from typing import Union @@ -570,7 +570,7 @@ if isinstance(h.pet, Dog): else: h.pet.paws + 1 -[builtins fixtures/isinstancelist.py] +[builtins fixtures/isinstancelist.pyi] [case testIsInstanceReturn] from typing import Union @@ -590,7 +590,7 @@ def bar() -> None: y = x + 'asdad' foo() -[builtins fixtures/isinstancelist.py] +[builtins fixtures/isinstancelist.pyi] [case testIsInstanceBadBreak] from typing import Union @@ -604,7 +604,7 @@ def foo() -> None: y = x + 'asdad' # E: Unsupported operand types for + (likely involving Union) foo() -[builtins fixtures/isinstancelist.py] +[builtins fixtures/isinstancelist.pyi] [out] main: note: In function "foo": [case testIsInstanceThreeUnion] @@ -622,7 +622,7 @@ while 1: x + 'a' # E: Unsupported operand types for + (likely involving Union) x + [1] # E: Unsupported operand types for + (likely involving Union) -[builtins fixtures/isinstancelist.py] +[builtins fixtures/isinstancelist.pyi] [case testIsInstanceThreeUnion2] from typing import Union, List @@ -639,7 +639,7 @@ while 1: x + 'a' # E: Unsupported operand types for + ("list" and "str") x + [1] # E: Unsupported operand types for + (likely involving Union) -[builtins fixtures/isinstancelist.py] +[builtins fixtures/isinstancelist.pyi] [case testIsInstanceThreeUnion3] from typing import Union, List @@ -657,7 +657,7 @@ while 1: x + 'a' x + [1] # E: Unsupported operand types for + (likely involving Union) -[builtins fixtures/isinstancelist.py] +[builtins fixtures/isinstancelist.pyi] [case testRemovingTypeRepeatedly] from typing import Union @@ -685,7 +685,7 @@ for i in [1, 2]: x + 'a' # E: Unsupported operand types for + (likely involving Union) -[builtins fixtures/isinstancelist.py] +[builtins fixtures/isinstancelist.pyi] @@ -710,7 +710,7 @@ x = foo() x + 1 # E: Unsupported operand types for + (likely involving Union) x + 'a' # E: Unsupported operand types for + (likely involving Union) -[builtins fixtures/isinstancelist.py] +[builtins fixtures/isinstancelist.pyi] [case testModifyLoop] from typing import Union @@ -727,7 +727,7 @@ x + 1 while 1: x + 1 # E: Unsupported operand types for + (likely involving Union) x = 'a' -[builtins fixtures/isinstancelist.py] +[builtins fixtures/isinstancelist.pyi] [case testModifyLoop2] from typing import Union @@ -746,7 +746,7 @@ for i in [1]: x + 1 # E: Unsupported operand types for + (likely involving Union) -[builtins fixtures/isinstancelist.py] +[builtins fixtures/isinstancelist.pyi] [case testModifyLoop3] @@ -772,7 +772,7 @@ for y in [1]: else: x + 1 x + 1 # E: Unsupported operand types for + (likely involving Union) -[builtins fixtures/isinstancelist.py] +[builtins fixtures/isinstancelist.pyi] [case testModifyLoopWhile4] from typing import Union @@ -801,7 +801,7 @@ else: x + 1 # E: Unsupported operand types for + (likely involving Union) x = 'a' x + 'a' -[builtins fixtures/isinstancelist.py] +[builtins fixtures/isinstancelist.pyi] [case testModifyLoopFor4] from typing import Union @@ -829,7 +829,7 @@ else: x + 1 # E: Unsupported operand types for + (likely involving Union) x = 'a' x + 'a' -[builtins fixtures/isinstancelist.py] +[builtins fixtures/isinstancelist.pyi] [case testModifyNestedLoop] from typing import Union @@ -857,7 +857,7 @@ while 1: else: x + 1 x + 1 # E: Unsupported operand types for + (likely involving Union) -[builtins fixtures/isinstancelist.py] +[builtins fixtures/isinstancelist.pyi] [case testModifyLoopLong] from typing import Union @@ -904,7 +904,7 @@ def bar() -> None: x.a # E: Some element of union has no attribute "a" x = 'a' -[builtins fixtures/isinstancelist.py] +[builtins fixtures/isinstancelist.pyi] [out] main: note: In function "bar": @@ -925,7 +925,7 @@ if isinstance(x, str): x + 1 x + 'a' # E: Unsupported operand types for + ("int" and "str") -[builtins fixtures/isinstancelist.py] +[builtins fixtures/isinstancelist.pyi] [case testUnreachableCode] @@ -935,7 +935,7 @@ while 1: x = 'a' # E: Incompatible types in assignment (expression has type "str", variable has type "int") break x = 'a' # Note: no error because unreachable code -[builtins fixtures/isinstancelist.py] +[builtins fixtures/isinstancelist.pyi] [case testUnreachableCode2] x = 1 @@ -947,7 +947,7 @@ while 1: else: continue x + 'a' -[builtins fixtures/isinstance.py] +[builtins fixtures/isinstance.pyi] [case testIsinstanceAnd] class A: @@ -960,7 +960,7 @@ x = B() # type: A if isinstance(x, B) and 1: x.flag -[builtins fixtures/isinstancelist.py] +[builtins fixtures/isinstancelist.pyi] [case testIsinstanceShortcircuit] class A: pass @@ -978,7 +978,7 @@ if not isinstance(x, B) or x.flag: pass if not isinstance(x, B) and x.flag: # E: "A" has no attribute "flag" pass -[builtins fixtures/isinstancelist.py] +[builtins fixtures/isinstancelist.pyi] [case testIsinstanceExpression] class A: pass @@ -991,7 +991,7 @@ x = B() # type: A x.flag if isinstance(x, B) else 0 0 if not isinstance(x, B) else x.flag 0 if isinstance(x, B) else x.flag # E: "A" has no attribute "flag" -[builtins fixtures/isinstancelist.py] +[builtins fixtures/isinstancelist.pyi] [case testIsinstanceMultiAnd] class A: @@ -1014,7 +1014,7 @@ if isinstance(x, B) and isinstance(y, C): else: x() # E: "A" not callable y() # E: "A" not callable -[builtins fixtures/isinstancelist.py] +[builtins fixtures/isinstancelist.pyi] [case testIsinstanceMultiAndSpecialCase] class A: @@ -1033,7 +1033,7 @@ if isinstance(x, B) and isinstance(y, int): 1() # type checking skipped if isinstance(y, int) and isinstance(x, B): 1() # type checking skipped -[builtins fixtures/isinstancelist.py] +[builtins fixtures/isinstancelist.pyi] [case testReturnWithCallExprAndIsinstance] @@ -1043,7 +1043,7 @@ def f(x: Union[int, str]) -> None: return foo() x() # E: "int" not callable def foo(): pass -[builtins fixtures/isinstancelist.py] +[builtins fixtures/isinstancelist.pyi] [out] main: note: In function "f": @@ -1054,7 +1054,7 @@ def f(a: bool, x: object) -> Optional[int]: return None reveal_type(x) # E: Revealed type is 'builtins.int' return x -[builtins fixtures/isinstance.py] +[builtins fixtures/isinstance.pyi] [out] main: note: In function "f": @@ -1065,7 +1065,7 @@ def g(a: bool, x: object) -> Optional[int]: return None reveal_type(x) # E: Revealed type is 'builtins.int' return x -[builtins fixtures/isinstance.py] +[builtins fixtures/isinstance.pyi] [out] main: note: In function "g": @@ -1075,7 +1075,7 @@ def h(a: bool, x: object) -> Optional[int]: if a or isinstance(x, int): return None return x # E: Incompatible return value type (got "object", expected "int") -[builtins fixtures/isinstance.py] +[builtins fixtures/isinstance.pyi] [out] main: note: In function "h": @@ -1086,7 +1086,7 @@ def f(x: Union[float, int]) -> None: pass if not isinstance(x, int): f(x) -[builtins fixtures/isinstance.py] +[builtins fixtures/isinstance.pyi] [case testIsinstanceWithOverlappingUnionType2] from typing import Union @@ -1097,14 +1097,14 @@ def f(x: Union[A, B]) -> None: pass if not isinstance(x, B): f(x) -[builtins fixtures/isinstance.py] +[builtins fixtures/isinstance.pyi] [case testAssertIsinstance] def f(x: object): assert isinstance(x, int) y = 0 # type: int y = x -[builtins fixtures/isinstance.py] +[builtins fixtures/isinstance.pyi] [case testUnionAssertIsinstance] from typing import Union @@ -1112,14 +1112,14 @@ def f(x: Union[str, int]): assert isinstance(x, int) y = 0 # type: int y = x -[builtins fixtures/isinstance.py] +[builtins fixtures/isinstance.pyi] [case testAnyAssertIsinstance] from typing import Any def f(x: Any): assert isinstance(x, int) # this should narrow x to type int x + "foo" # E: Unsupported operand types for + ("int" and "str") -[builtins fixtures/isinstance.py] +[builtins fixtures/isinstance.pyi] [out] main: note: In function "f": @@ -1128,7 +1128,7 @@ from typing import List, Union def f(x: Union[List[int], str]) -> None: if isinstance(x, list): x[0]() -[builtins fixtures/isinstancelist.py] +[builtins fixtures/isinstancelist.pyi] [out] main: note: In function "f": main:4: error: "int" not callable @@ -1153,5 +1153,15 @@ if isinstance(x2, A) or isinstance(x2, C): else: # unreachable 1() -[builtins fixtures/isinstance.py] +[builtins fixtures/isinstance.pyi] [out] +[case testComprehensionIsInstance] +from typing import List, Union +a = [] # type: List[Union[int, str]] +l = [x for x in a if isinstance(x, int)] +g = (x for x in a if isinstance(x, int)) +d = {0: x for x in a if isinstance(x, int)} +reveal_type(l) # E: Revealed type is 'builtins.list[builtins.int*]' +reveal_type(g) # E: Revealed type is 'typing.Iterator[builtins.int*]' +reveal_type(d) # E: Revealed type is 'builtins.dict[builtins.int*, builtins.int*]' +[builtins fixtures/isinstancelist.pyi] diff --git a/test-data/unit/check-kwargs.test b/test-data/unit/check-kwargs.test index 72e06cfb7241..29a9dc1b05b2 100644 --- a/test-data/unit/check-kwargs.test +++ b/test-data/unit/check-kwargs.test @@ -51,7 +51,7 @@ from typing import List def f(a: 'A', b: 'List[A]') -> None: pass f(b=[], a=A()) class A: pass -[builtins fixtures/list.py] +[builtins fixtures/list.pyi] [case testGivingSameKeywordArgumentTwice] import typing @@ -136,7 +136,7 @@ f(A(), B()) # E: Argument 2 to "f" has incompatible type "B"; expected "A" f(b=A()) # E: Argument 1 to "f" has incompatible type "A"; expected "B" class A: pass class B: pass -[builtins fixtures/list.py] +[builtins fixtures/list.pyi] [case testKeywordArgAfterVarArgsWithBothCallerAndCalleeVarArgs] from typing import List @@ -152,7 +152,7 @@ f(A(), b=A()) # E: Argument 2 to "f" has incompatible type "A"; expected "B" f(*a, b=A()) # E: Argument 2 to "f" has incompatible type "A"; expected "B" class A: pass class B: pass -[builtins fixtures/list.py] +[builtins fixtures/list.pyi] [case testCallingDynamicallyTypedFunctionWithKeywordArgs] import typing @@ -170,7 +170,7 @@ def f( **kwargs: 'A') -> None: d2 = kwargs # type: Dict[A, Any] # E: Incompatible types in assignment (expression has type Dict[str, A], variable has type Dict[A, Any]) d3 = kwargs # type: Dict[Any, str] # E: Incompatible types in assignment (expression has type Dict[str, A], variable has type Dict[Any, str]) class A: pass -[builtins fixtures/dict.py] +[builtins fixtures/dict.pyi] [out] main: note: In function "f": @@ -181,7 +181,7 @@ def f(**kwargs) -> None: d2 = kwargs # type: Dict[str, str] d3 = kwargs # type: Dict[A, Any] # E: Incompatible types in assignment (expression has type Dict[str, Any], variable has type Dict[A, Any]) class A: pass -[builtins fixtures/dict.py] +[builtins fixtures/dict.pyi] [out] main: note: In function "f": @@ -196,7 +196,7 @@ f(A()) # E: Too many arguments for "f" # Perhaps a better message would be "Too many *positional* arguments..." class A: pass class B: pass -[builtins fixtures/dict.py] +[builtins fixtures/dict.pyi] [case testCallingFunctionWithKeywordVarArgs] from typing import Dict @@ -209,7 +209,7 @@ f(**d2) # E: Argument 1 to "f" has incompatible type **Dict[str, B]; expe f(x=A(), **d2) # E: Argument 2 to "f" has incompatible type **Dict[str, B]; expected "A" class A: pass class B: pass -[builtins fixtures/dict.py] +[builtins fixtures/dict.pyi] [case testInvalidTypeForKeywordVarArg] from typing import Dict @@ -218,7 +218,7 @@ d = None # type: Dict[A, A] f(**d) # E: Keywords must be strings f(**A()) # E: Argument after ** must be a dictionary class A: pass -[builtins fixtures/dict.py] +[builtins fixtures/dict.pyi] [case testPassingKeywordVarArgsToNonVarArgsFunction] from typing import Any, Dict @@ -229,7 +229,7 @@ d2 = None # type: Dict[str, A] f(**d2) # E: Argument 1 to "f" has incompatible type **Dict[str, A]; expected "B" class A: pass class B: pass -[builtins fixtures/dict.py] +[builtins fixtures/dict.pyi] [case testBothKindsOfVarArgs] from typing import Any, List, Dict @@ -238,7 +238,7 @@ l = None # type: List[Any] d = None # type: Dict[Any, Any] f(*l, **d) class A: pass -[builtins fixtures/dict.py] +[builtins fixtures/dict.pyi] [case testKeywordArgumentAndCommentSignature] import typing @@ -265,7 +265,7 @@ f(z=1) f(x=1, y=1) f(x='', y=1) # E: Argument 1 to "f" has incompatible type "str"; expected "int" f(x=1, y='') # E: Argument 2 to "f" has incompatible type "str"; expected "int" -[builtins fixtures/dict.py] +[builtins fixtures/dict.pyi] [case testFunctionWithBareAsteriskAndVarArgs] class A: pass @@ -276,7 +276,7 @@ f(1, '', '') f(1, y=A(), z=B()) f(1, '', '', y=A(), z=B()) f(1, '', '', z=B(), y=A()) -[builtins fixtures/dict.py] +[builtins fixtures/dict.pyi] [case testFunctionWithBareAsteriskAndVarArgs2] class A: pass @@ -285,7 +285,7 @@ def f(x: int, *args: str, *, y: A = None, **kw: B) -> None: pass f(1, 2) # E: Argument 2 to "f" has incompatible type "int"; expected "str" f(1, y=1) # E: Argument 2 to "f" has incompatible type "int"; expected "A" f(1, z=1) # E: Argument 2 to "f" has incompatible type "int"; expected "B" -[builtins fixtures/dict.py] +[builtins fixtures/dict.pyi] [case testCallsWithStars] def f(a: int) -> None: @@ -304,9 +304,9 @@ f(**b) # E: Argument 1 to "f" has incompatible type **Dict[str, str]; expected " c = {0: 0} f(**c) # E: Keywords must be strings -[builtins fixtures/dict.py] +[builtins fixtures/dict.pyi] [case testCallStar2WithStar] def f(**k): pass f(*(1, 2)) # E: Too many arguments for "f" -[builtins fixtures/dict.py] +[builtins fixtures/dict.pyi] diff --git a/test-data/unit/check-lists.test b/test-data/unit/check-lists.test index e279926c2dc7..e832a2ed7c37 100644 --- a/test-data/unit/check-lists.test +++ b/test-data/unit/check-lists.test @@ -14,7 +14,7 @@ a1, [a1, [a1, b1]] = a1, [a1, [a1, c1]] # E: Incompatible types in assignment ( class A: pass class B: pass class C: pass -[builtins fixtures/list.py] +[builtins fixtures/list.pyi] [out] [case testNestedListAssignmentToTuple] @@ -28,7 +28,7 @@ a, b = [a, b, c] # E: Too many values to unpack (2 expected, 3 provided) class A: pass class B: pass class C: pass -[builtins fixtures/list.py] +[builtins fixtures/list.pyi] [out] [case testListAssignmentFromTuple] @@ -44,7 +44,7 @@ t = a, b class A: pass class B: pass class C: pass -[builtins fixtures/list.py] +[builtins fixtures/list.pyi] [out] [case testListAssignmentUnequalAmountToUnpack] @@ -59,7 +59,7 @@ def f() -> None: # needed because test parser tries to parse [a, b] as section h class A: pass class B: pass class C: pass -[builtins fixtures/list.py] +[builtins fixtures/list.pyi] [out] main: note: In function "f": @@ -71,4 +71,4 @@ b = [0, *a] reveal_type(b) # E: Revealed type is 'builtins.list[builtins.int*]' c = [*a, 0] reveal_type(c) # E: Revealed type is 'builtins.list[builtins.int*]' -[builtins fixtures/list.py] +[builtins fixtures/list.pyi] diff --git a/test-data/unit/check-modules.test b/test-data/unit/check-modules.test index 45c62e108b32..1fe861e40dc6 100644 --- a/test-data/unit/check-modules.test +++ b/test-data/unit/check-modules.test @@ -43,7 +43,7 @@ except m.Bad: # E: Exception type must be derived from BaseException [file m.py] class Err(BaseException): pass class Bad: pass -[builtins fixtures/exception.py] +[builtins fixtures/exception.pyi] [case testImportedExceptionType2] from m import Err, Bad @@ -57,7 +57,7 @@ except Bad: # E: Exception type must be derived from BaseException [file m.py] class Err(BaseException): pass class Bad: pass -[builtins fixtures/exception.py] +[builtins fixtures/exception.pyi] [case testImportWithinBlock] import typing @@ -162,7 +162,7 @@ m() # E: "module" not callable a = m # type: A # E: Incompatible types in assignment (expression has type "module", variable has type "A") m + None # E: Unsupported left operand type for + ("module") [file m.py] -[builtins fixtures/module.py] +[builtins fixtures/module.pyi] [case testNameDefinedInDifferentModule] import m, n @@ -172,7 +172,7 @@ m.x # E: "module" has no attribute "x" y = object() [file n.py] x = object() -[builtins fixtures/module.py] +[builtins fixtures/module.pyi] [case testChainedAssignmentAndImports] import m @@ -184,7 +184,7 @@ s = m.x # E: Incompatible types in assignment (expression has type "int", variab s = m.y # E: Incompatible types in assignment (expression has type "int", variable has type "str") [file m.py] x = y = 1 -[builtins fixtures/primitives.py] +[builtins fixtures/primitives.pyi] [case testConditionalFunctionDefinitionAndImports] import m @@ -329,7 +329,7 @@ x.nonexistent.foo x.z [file x.py] import nonexistent -[builtins fixtures/module.py] +[builtins fixtures/module.pyi] [out] main:1: note: In module imported here: tmp/x.py:1: error: Cannot find module named 'nonexistent' @@ -409,12 +409,12 @@ __all__.append('c') __all__.extend(('d', 'e')) a = b = c = d = e = f = _g = 1 -[builtins fixtures/module_all.py] +[builtins fixtures/module_all.pyi] [case testAllMustBeSequenceStr] import typing __all__ = [1, 2, 3] -[builtins fixtures/module_all.py] +[builtins fixtures/module_all.pyi] [out] main: error: Type of __all__ must be Sequence[str], not List[int] @@ -637,7 +637,7 @@ else: m.f(1) # E: Argument 1 to "f" has incompatible type "int"; expected "str" [file m.py] def f(x: str) -> None: pass -[builtins fixtures/module.py] +[builtins fixtures/module.pyi] [out] [case testConditionalImportAndAssignInvalidToModule] @@ -646,7 +646,7 @@ if object(): else: m = 1 # E: Incompatible types in assignment (expression has type "int", variable has type "module") [file m.py] -[builtins fixtures/module.py] +[builtins fixtures/module.pyi] [out] [case testImportAndAssignToModule] @@ -655,7 +655,7 @@ m = None m.f(1) # E: Argument 1 to "f" has incompatible type "int"; expected "str" [file m.py] def f(x: str) -> None: pass -[builtins fixtures/module.py] +[builtins fixtures/module.pyi] [out] @@ -726,22 +726,22 @@ tmp/bar.py:1: error: Module has no attribute 'B' [case testImportSuppressedWhileAlmostSilent] # cmd: mypy -m main -[file main.py] # options: silent_imports almost_silent +[file main.py] import mod [file mod.py] -[builtins fixtures/module.py] +[builtins fixtures/module.pyi] [out] -tmp/main.py:2: note: Import of 'mod' silently ignored -tmp/main.py:2: note: (Using --silent-imports, module not passed on command line) -tmp/main.py:2: note: (This note courtesy of --almost-silent) +tmp/main.py:1: note: Import of 'mod' silently ignored +tmp/main.py:1: note: (Using --silent-imports, module not passed on command line) +tmp/main.py:1: note: (This note courtesy of --almost-silent) [case testAncestorSuppressedWhileAlmostSilent] # cmd: mypy -m foo.bar -[file foo/bar.py] # options: silent_imports almost_silent +[file foo/bar.py] [file foo/__init__.py] -[builtins fixtures/module.py] +[builtins fixtures/module.pyi] [out] tmp/foo/bar.py: note: Ancestor package 'foo' silently ignored tmp/foo/bar.py: note: (Using --silent-imports, submodule passed on command line) @@ -749,8 +749,8 @@ tmp/foo/bar.py: note: (This note brought to you by --almost-silent) [case testStubImportNonStubWhileSilent] # cmd: mypy -m main -[file main.py] # options: silent_imports +[file main.py] from stub import x # Permitted from other import y # Disallowed x + '' # Error here @@ -761,9 +761,9 @@ from non_stub import x x = 42 [file other.py] y = 42 -[builtins fixtures/module.py] +[builtins fixtures/module.pyi] [out] -tmp/main.py:4: error: Unsupported left operand type for + ("int") +tmp/main.py:3: error: Unsupported left operand type for + ("int") [case testSuperclassInImportCycle] import a diff --git a/test-data/unit/check-namedtuple.test b/test-data/unit/check-namedtuple.test index d51f078c8fd4..9776f83d4879 100644 --- a/test-data/unit/check-namedtuple.test +++ b/test-data/unit/check-namedtuple.test @@ -162,7 +162,7 @@ i, i = l[0] # E: Need more than 1 value to unpack (2 expected) l = [A(1)] a = (1,) # E: Incompatible types in assignment (expression has type "Tuple[int]", \ variable has type "A") -[builtins fixtures/list.py] +[builtins fixtures/list.pyi] [case testNamedTupleMissingClassAttribute] import collections @@ -172,7 +172,7 @@ MyNamedTuple.x # E: "MyNamedTuple" has no attribute "x" [case testNamedTupleEmptyItems] from typing import NamedTuple A = NamedTuple('A', []) -[builtins fixtures/list.py] +[builtins fixtures/list.pyi] [case testNamedTupleProperty] from typing import NamedTuple @@ -184,4 +184,4 @@ class B(A): class C(B): pass B(1).b C(2).b -[builtins fixtures/property.py] +[builtins fixtures/property.pyi] diff --git a/test-data/unit/check-newtype.test b/test-data/unit/check-newtype.test index 59c36690777d..17775995a4c4 100644 --- a/test-data/unit/check-newtype.test +++ b/test-data/unit/check-newtype.test @@ -47,7 +47,7 @@ b = TwoTuple(("a", 3)) # E: Argument 1 to "TwoTuple" has incompatible type "Tup reveal_type(a[0]) # E: Revealed type is 'builtins.int' reveal_type(a[1]) # E: Revealed type is 'builtins.str' -[builtins fixtures/tuple.py] +[builtins fixtures/tuple.pyi] [out] [case testNewTypeWithLists] @@ -69,7 +69,7 @@ reveal_type(foo) # E: Revealed type is '__main__.IdList' reveal_type(bar) # E: Revealed type is '__main__.IdList' reveal_type(baz) # E: Revealed type is 'builtins.list[__main__.UserId*]' -[builtins fixtures/list.py] +[builtins fixtures/list.pyi] [out] [case testNewTypeWithGenerics] @@ -196,7 +196,7 @@ UserId = NewType('UserId', int) from typing import NewType UserId = NewType('UserId', int) -[builtins fixtures/list.py] +[builtins fixtures/list.pyi] [out] [case testNewTypeWithIncremental] @@ -265,7 +265,7 @@ Foo = NewType('Foo', Union[int, float]) # E: Argument 2 to NewType(...) must be from typing import NewType, Type Foo = NewType('Foo', Type[int]) # E: Argument 2 to NewType(...) must be subclassable (got Type[builtins.int]) a = Foo(type(3)) -[builtins fixtures/args.py] +[builtins fixtures/args.pyi] [out] [case testNewTypeWithTypeVarsFails] @@ -273,7 +273,7 @@ from typing import NewType, TypeVar, List T = TypeVar('T') A = NewType('A', T) B = NewType('B', List[T]) -[builtins fixtures/list.py] +[builtins fixtures/list.pyi] [out] main:3: error: Invalid type "__main__.T" main:3: error: Argument 2 to NewType(...) must be subclassable (got T?) diff --git a/test-data/unit/check-optional.test b/test-data/unit/check-optional.test index 75f1f1220291..8d0ec479bf49 100644 --- a/test-data/unit/check-optional.test +++ b/test-data/unit/check-optional.test @@ -39,7 +39,7 @@ if isinstance(x, int): reveal_type(x) # E: Revealed type is 'builtins.int' else: reveal_type(x) # E: Revealed type is 'builtins.None' -[builtins fixtures/isinstance.py] +[builtins fixtures/isinstance.pyi] [case testIfCases] from typing import Optional @@ -48,7 +48,7 @@ if x: reveal_type(x) # E: Revealed type is 'builtins.int' else: reveal_type(x) # E: Revealed type is 'Union[builtins.int, builtins.None]' -[builtins fixtures/bool.py] +[builtins fixtures/bool.pyi] [case testIfNotCases] from typing import Optional @@ -57,7 +57,7 @@ if not x: reveal_type(x) # E: Revealed type is 'Union[builtins.int, builtins.None]' else: reveal_type(x) # E: Revealed type is 'builtins.int' -[builtins fixtures/bool.py] +[builtins fixtures/bool.pyi] [case testIsNotNoneCases] from typing import Optional @@ -66,7 +66,7 @@ if x is not None: reveal_type(x) # E: Revealed type is 'builtins.int' else: reveal_type(x) # E: Revealed type is 'builtins.None' -[builtins fixtures/bool.py] +[builtins fixtures/bool.pyi] [case testIsNoneCases] from typing import Optional @@ -75,7 +75,7 @@ if x is None: reveal_type(x) # E: Revealed type is 'builtins.None' else: reveal_type(x) # E: Revealed type is 'builtins.int' -[builtins fixtures/bool.py] +[builtins fixtures/bool.pyi] [case testLambdaReturningNone] f = lambda: None @@ -100,6 +100,23 @@ f(None) [out] main: note: In function "f": +[case testInferOptionalFromDefaultNoneComment] +def f(x=None): + # type: (int) -> None + x + 1 # E: Unsupported left operand type for + (some union) +f(None) +[out] +main: note: In function "f": + +[case testInferOptionalFromDefaultNoneCommentWithFastParser] +# options: fast_parser +def f(x=None): + # type: (int) -> None + x + 1 # E: Unsupported left operand type for + (some union) +f(None) +[out] +main: note: In function "f": + [case testInferOptionalType] x = None if bool(): @@ -109,7 +126,7 @@ if bool(): reveal_type(x) # E: Revealed type is 'builtins.int' # out of scope of the assignment, it's an Optional[int] reveal_type(x) # E: Revealed type is 'Union[builtins.int, builtins.None]' -[builtins fixtures/bool.py] +[builtins fixtures/bool.pyi] [case testInferOptionalTypeLocallyBound] x = None @@ -128,25 +145,25 @@ reveal_type(x) # E: Revealed type is 'Union[builtins.int, builtins.None]' x = [None] x.append(1) reveal_type(x) # E: Revealed type is 'builtins.list[Union[builtins.int, builtins.None]]' -[builtins fixtures/list.py] +[builtins fixtures/list.pyi] [case testInferNonOptionalListType] x = [] x.append(1) x() # E: List[int] not callable -[builtins fixtures/list.py] +[builtins fixtures/list.pyi] [case testInferOptionalDictKeyValueTypes] x = {None: None} x["bar"] = 1 reveal_type(x) # E: Revealed type is 'builtins.dict[Union[builtins.str, builtins.None], Union[builtins.int, builtins.None]]' -[builtins fixtures/dict.py] +[builtins fixtures/dict.pyi] [case testInferNonOptionalDictType] x = {} x["bar"] = 1 x() # E: Dict[str, int] not callable -[builtins fixtures/dict.py] +[builtins fixtures/dict.pyi] [case testNoneClassVariable] from typing import Optional @@ -315,3 +332,26 @@ x = f # type: Callable[[], None] [case testOptionalCallable] from typing import Callable, Optional T = Optional[Callable[..., None]] + +[case testAnyTypeInPartialTypeList] +# options: check_untyped_defs +def f(): ... + +def lookup_field(name, obj): + try: + pass + except: + attr = f() + else: + attr = None +[out] +main: note: In function "lookup_field": +main:10: error: Need type annotation for variable + +[case testTernaryWithNone] +reveal_type(None if bool() else 0) # E: Revealed type is 'Union[builtins.int, builtins.None]' +[builtins fixtures/bool.pyi] + +[case testListWithNone] +reveal_type([0, None, 0]) # E: Revealed type is 'builtins.list[Union[builtins.int, builtins.None]]' +[builtins fixtures/list.pyi] diff --git a/test-data/unit/check-overloading.test b/test-data/unit/check-overloading.test index e58bdb6d48e5..a7e11597c70d 100644 --- a/test-data/unit/check-overloading.test +++ b/test-data/unit/check-overloading.test @@ -225,7 +225,7 @@ def f(x: A) -> None: pass def f(x: Callable[[], None]) -> None: pass f(A()) -[builtins fixtures/function.py] +[builtins fixtures/function.pyi] [case testVarArgsOverload] from typing import overload, Any @@ -241,7 +241,7 @@ f(B(), B, B) f(object()) # E: No overload variant of "f" matches argument types [builtins.object] class A: pass class B: pass -[builtins fixtures/list.py] +[builtins fixtures/list.pyi] [case testVarArgsOverload2] from typing import overload @@ -255,7 +255,7 @@ f(A(), A(), B()) # E: No overload variant of "f" matches argument types [__main_ f(A(), B(), A()) # E: No overload variant of "f" matches argument types [__main__.A, __main__.B, __main__.A] class A: pass class B: pass -[builtins fixtures/list.py] +[builtins fixtures/list.pyi] [case testOverloadWithTypeObject] from typing import overload @@ -267,7 +267,7 @@ f(A(), B) f(B(), A) class A: pass class B: pass -[builtins fixtures/function.py] +[builtins fixtures/function.pyi] [case testOverloadedInitAndTypeObjectInOverload] from typing import overload @@ -304,7 +304,7 @@ m = 1 n = 'x' # E: Incompatible types in assignment (expression has type "str", variable has type "int") m = 'x' # E: Incompatible types in assignment (expression has type "str", variable has type "int") f(list_object) # E: Argument 1 to "f" has incompatible type List[object]; expected List[int] -[builtins fixtures/list.py] +[builtins fixtures/list.pyi] [case testOverlappingOverloadSignatures] from typing import overload @@ -490,7 +490,7 @@ f(1.1) f('') f(1) f(()) # E: No overload variant of "f" matches argument types [Tuple[]] -[builtins fixtures/primitives.py] +[builtins fixtures/primitives.pyi] [out] [case testOverloadingVariableInputs] @@ -503,7 +503,7 @@ f(1) f(1, 2) z = (1, 2) f(*z) -[builtins fixtures/primitives.py] +[builtins fixtures/primitives.pyi] [out] [case testTypeInferenceSpecialCaseWithOverloading] @@ -560,7 +560,7 @@ f(y=[1], x=0)() # E: "int" not callable f(y=[''], x=0)() # E: "int" not callable a = f(y=[['']], x=0) # E: List item 0 has incompatible type List[str] a() # E: "int" not callable -[builtins fixtures/list.py] +[builtins fixtures/list.pyi] [case testOverloadWithDerivedFromAny] from typing import Any, overload @@ -591,7 +591,7 @@ f('x')() # E: "str" not callable f(1)() # E: "bool" not callable f(1.1) # E: No overload variant of "f" matches argument types [builtins.float] f(mystr())() # E: "mystr" not callable -[builtins fixtures/primitives.py] +[builtins fixtures/primitives.pyi] [case testOverloadedCallWithVariableTypes] from typing import overload, TypeVar, List @@ -610,7 +610,7 @@ def g(x: U, y: V) -> None: a = f([x]) # E: "f" does not return a value f([y]) # E: Type argument 1 of "f" has incompatible value "V" f([x, y]) # E: Type argument 1 of "f" has incompatible value "object" -[builtins fixtures/list.py] +[builtins fixtures/list.pyi] [out] main: note: In function "g": @@ -650,7 +650,7 @@ g('foo', b'bar') # E: Type argument 1 of "g" has incompatible value "object" g(1) g(1, 'foo') g(1, 'foo', b'bar') # E: Type argument 1 of "g" has incompatible value "object" -[builtins fixtures/primitives.py] +[builtins fixtures/primitives.pyi] [case testBadOverlapWithTypeVarsWithValues] from typing import overload, TypeVar @@ -660,7 +660,7 @@ AnyStr = TypeVar('AnyStr', bytes, str) def f(x: AnyStr) -> None: pass # E: Overloaded function signatures 1 and 2 overlap with incompatible return types @overload def f(x: str) -> bool: pass -[builtins fixtures/primitives.py] +[builtins fixtures/primitives.pyi] [case testOverlappingOverloadCounting] from typing import overload @@ -755,4 +755,4 @@ x = ('2', '3') # type: Tuple[str, ...] f(1, x) y = (2, 3) # type: Tuple[int, ...] f(1, y) # E: Argument 2 to "f" has incompatible type Tuple[int, ...]; expected Tuple[str, ...] -[builtins fixtures/tuple.py] +[builtins fixtures/tuple.pyi] diff --git a/test-data/unit/check-python2.test b/test-data/unit/check-python2.test index 09412974a088..4980d47210d2 100644 --- a/test-data/unit/check-python2.test +++ b/test-data/unit/check-python2.test @@ -7,7 +7,7 @@ u = unicode() s = '' s = u'foo' # E: Incompatible types in assignment (expression has type "unicode", variable has type "str") s = b'foo' -[builtins_py2 fixtures/python2.py] +[builtins_py2 fixtures/python2.pyi] [case testTypeVariableUnicode] from typing import TypeVar @@ -45,7 +45,7 @@ def f(x: unicode) -> None: pass f('') f(u'') f(b'') -[builtins_py2 fixtures/python2.py] +[builtins_py2 fixtures/python2.pyi] [case testStaticMethodWithCommentSignature] class A: @@ -54,21 +54,21 @@ class A: return '' A.f(1) A.f('') # E: Argument 1 to "f" of "A" has incompatible type "str"; expected "int" -[builtins_py2 fixtures/staticmethod.py] +[builtins_py2 fixtures/staticmethod.pyi] [case testRaiseTuple] import typing raise BaseException, "a" raise BaseException, "a", None raise BaseException, "a", None, None # E: Exception must be derived from BaseException -[builtins_py2 fixtures/exception.py] +[builtins_py2 fixtures/exception.pyi] [case testTryExceptWithTuple] try: None except BaseException, e: e() # E: "BaseException" not callable -[builtins_py2 fixtures/exception.py] +[builtins_py2 fixtures/exception.pyi] [case testAlternateNameSuggestions] class Foo(object): @@ -110,7 +110,7 @@ def f(x, (y, z)): # type: (object, Tuple[int, str]) -> None z() # E f(object(), (1, '')) f(1, 1) # E -[builtins_py2 fixtures/tuple.py] +[builtins_py2 fixtures/tuple.pyi] [out] main: note: In function "f": main:3: error: "object" not callable @@ -128,7 +128,7 @@ def f(x, (y, (a, b))): # type: (object, Tuple[int, Tuple[str, int]]) -> None b() # E f(object(), (1, ('', 2))) f(1, 1) # E -[builtins fixtures/tuple.py] +[builtins fixtures/tuple.pyi] [out] main: note: In function "f": main:3: error: "object" not callable diff --git a/test-data/unit/check-statements.test b/test-data/unit/check-statements.test index e4b025570ea2..b0e9b26183e5 100644 --- a/test-data/unit/check-statements.test +++ b/test-data/unit/check-statements.test @@ -115,7 +115,7 @@ if b: pass class A: pass -[builtins fixtures/bool.py] +[builtins fixtures/bool.pyi] -- Loops @@ -134,7 +134,7 @@ while b: b = b class A: pass -[builtins fixtures/bool.py] +[builtins fixtures/bool.pyi] [out] main:5: error: Incompatible types in assignment (expression has type "bool", variable has type "A") main:7: error: Incompatible types in assignment (expression has type "bool", variable has type "A") @@ -149,7 +149,7 @@ else: a = b # Fail class A: pass -[builtins fixtures/list.py] +[builtins fixtures/list.pyi] [out] main:5: error: Incompatible types in assignment (expression has type "object", variable has type "A") main:7: error: Incompatible types in assignment (expression has type "object", variable has type "A") @@ -158,14 +158,14 @@ main:7: error: Incompatible types in assignment (expression has type "object", v import typing while None: break -[builtins fixtures/bool.py] +[builtins fixtures/bool.pyi] [out] [case testContinueStatement] import typing while None: continue -[builtins fixtures/bool.py] +[builtins fixtures/bool.pyi] [out] @@ -328,7 +328,7 @@ raise e raise f class A: pass class MyError(BaseException): pass -[builtins fixtures/exception.py] +[builtins fixtures/exception.pyi] [out] main:5: error: Exception must be derived from BaseException @@ -342,7 +342,7 @@ raise MyError raise A # E: Exception must be derived from BaseException raise object # E: Exception must be derived from BaseException raise f # E: Exception must be derived from BaseException -[builtins fixtures/exception.py] +[builtins fixtures/exception.pyi] [case testRaiseFromStatement] @@ -354,7 +354,7 @@ raise e from e raise e from f class A: pass class MyError(BaseException): pass -[builtins fixtures/exception.py] +[builtins fixtures/exception.pyi] [case testRaiseFromClassobject] import typing @@ -366,7 +366,7 @@ raise BaseException from MyError raise BaseException from A # E: Exception must be derived from BaseException raise BaseException from object # E: Exception must be derived from BaseException raise BaseException from f # E: Exception must be derived from BaseException -[builtins fixtures/exception.py] +[builtins fixtures/exception.pyi] [case testTryFinallyStatement] import typing @@ -389,7 +389,7 @@ except BaseException as e: e = o # Fail class A: pass class B: pass -[builtins fixtures/exception.py] +[builtins fixtures/exception.pyi] [out] main:7: error: Incompatible types in assignment (expression has type "object", variable has type "BaseException") @@ -414,7 +414,7 @@ x = object() # Fail x = A() # Fail x = BaseException() class A: pass -[builtins fixtures/exception.py] +[builtins fixtures/exception.pyi] [out] main:3: error: Incompatible types in assignment (expression has type "BaseException", variable has type "A") main:4: error: Incompatible types in assignment (expression has type "object", variable has type "A") @@ -428,7 +428,7 @@ try: except BaseException as e: e = object() # Fail e = BaseException() -[builtins fixtures/exception.py] +[builtins fixtures/exception.pyi] [out] main:5: error: Incompatible types in assignment (expression has type "object", variable has type "BaseException") @@ -440,7 +440,7 @@ except Err as e: e = BaseException() # Fail e = Err() class Err(BaseException): pass -[builtins fixtures/exception.py] +[builtins fixtures/exception.pyi] [out] main:5: error: Incompatible types in assignment (expression has type "BaseException", variable has type "Err") @@ -454,7 +454,7 @@ except Err as f: f = BaseException() # Fail f = Err() class Err(BaseException): pass -[builtins fixtures/exception.py] +[builtins fixtures/exception.pyi] [out] main:7: error: Incompatible types in assignment (expression has type "BaseException", variable has type "Err") @@ -471,7 +471,7 @@ except Err as f: class A: pass class B: pass class Err(BaseException): pass -[builtins fixtures/exception.py] +[builtins fixtures/exception.pyi] [out] main:3: error: Incompatible types in assignment (expression has type "B", variable has type "A") main:5: error: Incompatible types in assignment (expression has type "A", variable has type "BaseException") @@ -488,7 +488,7 @@ def f() -> None: f = BaseException() # Fail f = Err() class Err(BaseException): pass -[builtins fixtures/exception.py] +[builtins fixtures/exception.pyi] [out] main: note: In function "f": main:5: error: Incompatible types in assignment (expression has type "object", variable has type "BaseException") @@ -502,7 +502,7 @@ def f() -> None: except: raise x + 'a' # E: Unsupported left operand type for + ("int") -[builtins fixtures/exception.py] +[builtins fixtures/exception.pyi] [out] main: note: In function "f": @@ -512,7 +512,7 @@ try: pass except BaseException: pass else: object(None) # E: Too many arguments for "object" -[builtins fixtures/exception.py] +[builtins fixtures/exception.pyi] [case testRedefinedFunctionInTryWithElse-skip] def f() -> None: pass @@ -528,7 +528,7 @@ except BaseException: f3 = f else: def f3() -> None: pass -[builtins fixtures/exception.py] +[builtins fixtures/exception.pyi] [out] main:7: error: Incompatible redefinition (redefinition with type Callable[[], str], original type Callable[[], None]) @@ -538,7 +538,7 @@ try: -None # E: Unsupported operand type for unary - (None) except: ~None # E: Unsupported operand type for ~ (None) -[builtins fixtures/exception.py] +[builtins fixtures/exception.pyi] [case testRaiseWithoutArgument] import typing @@ -546,7 +546,7 @@ try: None except: raise -[builtins fixtures/exception.py] +[builtins fixtures/exception.pyi] [case testExceptWithMultipleTypes] import typing @@ -562,7 +562,7 @@ except (E1, (E2,)): pass # E: Exception type must be derived from BaseException except (E1, E2): pass except ((E1, E2)): pass except (((E1, E2))): pass -[builtins fixtures/exception.py] +[builtins fixtures/exception.pyi] [case testExceptWithMultipleTypes2] import typing @@ -578,7 +578,7 @@ except (E2, E1) as e2: b = e2 # type: E2 # E: Incompatible types in assignment (expression has type "E1", variable has type "E2") except (E1, E2, int) as e3: # E: Exception type must be derived from BaseException pass -[builtins fixtures/exception.py] +[builtins fixtures/exception.pyi] [case testExceptWithMultipleTypes3] import typing @@ -594,7 +594,7 @@ except (E1_1, E1_2) as e2: a = e2 # type: E1 b = e2 # type: E1_1 # E: Incompatible types in assignment (expression has type "Union[E1_1, E1_2]", variable has type "E1_1") c = e2 # type: E1_2 # E: Incompatible types in assignment (expression has type "Union[E1_1, E1_2]", variable has type "E1_2") -[builtins fixtures/exception.py] +[builtins fixtures/exception.pyi] [case testExceptWithAnyTypes] from typing import Any @@ -629,7 +629,7 @@ except (NotBaseDerived, E1, E2) as e6: # E: Exception type must be derived from pass except (E1, E2, NotBaseDerived) as e6: # E: Exception type must be derived from BaseException pass -[builtins fixtures/exception.py] +[builtins fixtures/exception.pyi] [case testReuseTryExceptionVariable] import typing @@ -643,7 +643,7 @@ try: pass except E2 as e: pass e + 1 # E: Trying to read deleted variable 'e' e = E1() # E: Assignment to variable 'e' outside except: block -[builtins fixtures/exception.py] +[builtins fixtures/exception.pyi] [case testReuseDefinedTryExceptionVariable] import typing @@ -655,7 +655,7 @@ try: pass except E1 as e: pass e = 1 # E: Assignment to variable 'e' outside except: block e = E1() # E: Assignment to variable 'e' outside except: block -[builtins fixtures/exception.py] +[builtins fixtures/exception.pyi] [case testArbitraryExpressionAsExceptionType] import typing @@ -664,7 +664,7 @@ try: pass except a as b: b = BaseException() b = object() # E: Incompatible types in assignment (expression has type "object", variable has type "BaseException") -[builtins fixtures/exception.py] +[builtins fixtures/exception.pyi] [case testInvalidExceptionCallable] import typing @@ -672,7 +672,7 @@ def exc() -> BaseException: pass try: pass except exc as e: pass # E: Exception type must be derived from BaseException except BaseException() as b: pass # E: Exception type must be derived from BaseException -[builtins fixtures/exception.py] +[builtins fixtures/exception.pyi] [case testTupleValueAsExceptionType] import typing @@ -698,7 +698,7 @@ except exs2 as e2: exs3 = (E1, (E1_1, (E1_2,))) try: pass except exs3 as e3: pass # E: Exception type must be derived from BaseException -[builtins fixtures/exception.py] +[builtins fixtures/exception.pyi] [case testInvalidTupleValueAsExceptionType] import typing @@ -709,7 +709,7 @@ class E2(E1): pass exs1 = (E1, E2, int) try: pass except exs1 as e: pass # E: Exception type must be derived from BaseException -[builtins fixtures/exception.py] +[builtins fixtures/exception.pyi] [case testOverloadedExceptionType] from typing import overload @@ -723,7 +723,7 @@ try: except E as e: e = E() e = BaseException() # E: Incompatible types in assignment (expression has type "BaseException", variable has type "E") -[builtins fixtures/exception.py] +[builtins fixtures/exception.pyi] [case testExceptionWithAnyBaseClass] from typing import Any @@ -731,7 +731,7 @@ E = None # type: Any class EE(E): pass raise EE() raise EE -[builtins fixtures/exception.py] +[builtins fixtures/exception.pyi] -- Del statement @@ -769,14 +769,14 @@ a = 1 a + 1 del a a + 1 # E: Trying to read deleted variable 'a' -[builtins fixtures/ops.py] +[builtins fixtures/ops.pyi] [case testDelStatementWithAssignmentTuple] a = 1 b = 1 del (a, b) b + 1 # E: Trying to read deleted variable 'b' -[builtins fixtures/ops.py] +[builtins fixtures/ops.pyi] [case testDelStatementWithAssignmentClass] class C: @@ -787,7 +787,7 @@ c.a = 1 c.a + 1 del c.a c.a + 1 -[builtins fixtures/ops.py] +[builtins fixtures/ops.pyi] -- Yield statement -- --------------- @@ -798,7 +798,7 @@ from typing import Iterator def f() -> Iterator[int]: yield 1 yield '' # E: Incompatible types in yield (actual type "str", expected type "int") -[builtins fixtures/for.py] +[builtins fixtures/for.pyi] [out] main: note: In function "f": @@ -806,20 +806,20 @@ main: note: In function "f": from typing import Generator def f() -> Generator[int, None, None]: yield 1 -[builtins fixtures/for.py] +[builtins fixtures/for.pyi] [out] [case testYieldInFunctionReturningIterable] from typing import Iterable def f() -> Iterable[int]: yield 1 -[builtins fixtures/for.py] +[builtins fixtures/for.pyi] [out] [case testYieldInFunctionReturningObject] def f() -> object: yield 1 -[builtins fixtures/for.py] +[builtins fixtures/for.pyi] [out] [case testYieldInFunctionReturningAny] @@ -844,7 +844,7 @@ def f(): import typing def f() -> int: # E: The return type of a generator function should be "Generator" or one of its supertypes yield 1 -[builtins fixtures/for.py] +[builtins fixtures/for.pyi] [out] main: note: In function "f": @@ -853,7 +853,7 @@ from typing import List, Iterator def f() -> 'Iterator[List[int]]': yield [] yield [object()] # E: List item 0 has incompatible type "object" -[builtins fixtures/for.py] +[builtins fixtures/for.pyi] [out] main: note: In function "f": @@ -862,19 +862,19 @@ from typing import Iterator def f() -> Iterator[int]: yield 1 return -[builtins fixtures/for.py] +[builtins fixtures/for.pyi] [case testYieldWithNoValue] from typing import Iterator def f() -> Iterator[None]: yield -[builtins fixtures/for.py] +[builtins fixtures/for.pyi] [case testYieldWithNoValueWhenValueRequired] from typing import Iterator def f() -> Iterator[int]: yield # E: Yield value expected -[builtins fixtures/for.py] +[builtins fixtures/for.pyi] [out] main: note: In function "f": @@ -882,7 +882,7 @@ main: note: In function "f": from typing import Iterator def f() -> Iterator[None]: yield None # E: Incompatible types in yield (actual type None, expected type None) -[builtins fixtures/for.py] +[builtins fixtures/for.pyi] [out] main: note: In function "f": @@ -947,7 +947,7 @@ def g() -> Iterator[List[int]]: def f() -> Iterator[List[int]]: yield from g() yield from [1, 2, 3] # E: Incompatible types in "yield from" (actual type "int", expected type List[int]) -[builtins fixtures/for.py] +[builtins fixtures/for.pyi] [out] main: note: In function "f": @@ -1064,7 +1064,7 @@ with A() as (a, b): a = 1 b = '' a = b # E: Incompatible types in assignment (expression has type "str", variable has type "int") -[builtins fixtures/tuple.py] +[builtins fixtures/tuple.pyi] -- Chained assignment @@ -1088,7 +1088,7 @@ def f() -> None: y = 'x' x = y = 'x' # E: Incompatible types in assignment (expression has type "str", variable has type "int") x = y = 1 # E: Incompatible types in assignment (expression has type "int", variable has type "str") -[builtins fixtures/primitives.py] +[builtins fixtures/primitives.pyi] [out] main: note: In function "f": @@ -1115,7 +1115,7 @@ nc = cs class A: pass class B: pass -[builtins fixtures/list.py] +[builtins fixtures/list.pyi] -- Type aliases diff --git a/test-data/unit/check-super.test b/test-data/unit/check-super.test index 0f2d7e7af466..39a1c63a87ee 100644 --- a/test-data/unit/check-super.test +++ b/test-data/unit/check-super.test @@ -94,7 +94,7 @@ class B(A): super().__new__(cls, x) # E B('') B(1) # E -[builtins fixtures/__new__.py] +[builtins fixtures/__new__.pyi] [out] main: note: In member "__new__" of class "B": main:8: error: Argument 2 to "__new__" of "A" has incompatible type "str"; expected "int" diff --git a/test-data/unit/check-tuples.test b/test-data/unit/check-tuples.test index ab35d92961de..ceb125ea2c63 100644 --- a/test-data/unit/check-tuples.test +++ b/test-data/unit/check-tuples.test @@ -25,7 +25,7 @@ t5 = t5 class A: pass class B: pass -[builtins fixtures/tuple.py] +[builtins fixtures/tuple.pyi] [case testTupleSubtyping] from typing import Tuple @@ -43,7 +43,7 @@ t1 = t3 class A: pass class B(A): pass -[builtins fixtures/tuple.py] +[builtins fixtures/tuple.pyi] [case testTupleCompatibilityWithOtherTypes] from typing import Tuple @@ -60,7 +60,7 @@ o = t t = None class A: pass -[builtins fixtures/tuple.py] +[builtins fixtures/tuple.pyi] [case testNestedTupleTypes] from typing import Tuple @@ -72,7 +72,7 @@ t1 = t2 class A: pass class B(A): pass -[builtins fixtures/tuple.py] +[builtins fixtures/tuple.pyi] [case testNestedTupleTypes2] from typing import Tuple @@ -84,7 +84,7 @@ t1 = t2 class A: pass class B(A): pass -[builtins fixtures/tuple.py] +[builtins fixtures/tuple.pyi] [case testSubtypingWithNamedTupleType] from typing import Tuple @@ -95,14 +95,14 @@ t1 = t2 # E: Incompatible types in assignment (expression has type Tuple[Any, .. t2 = t1 class A: pass -[builtins fixtures/tuple.py] +[builtins fixtures/tuple.pyi] [case testTupleInitializationWithNone] from typing import Tuple t = None # type: Tuple[A, A] t = None class A: pass -[builtins fixtures/tuple.py] +[builtins fixtures/tuple.pyi] -- Tuple expressions @@ -133,7 +133,7 @@ t3 = (None, None) class A: pass class B: pass class C(B): pass -[builtins fixtures/tuple.py] +[builtins fixtures/tuple.pyi] [case testVoidValueInTuple] import typing @@ -141,7 +141,7 @@ import typing (f(), None) # E: "f" does not return a value def f() -> None: pass -[builtins fixtures/tuple.py] +[builtins fixtures/tuple.pyi] -- Indexing @@ -180,7 +180,7 @@ class B: pass class C: pass class D: pass class E: pass -[builtins fixtures/tuple.py] +[builtins fixtures/tuple.pyi] [case testIndexingTuplesWithNegativeIntegers] from typing import Tuple @@ -200,7 +200,7 @@ a = t2[(-1)] class A: pass class B: pass -[builtins fixtures/tuple.py] +[builtins fixtures/tuple.pyi] [case testAssigningToTupleItems] from typing import Tuple @@ -213,7 +213,7 @@ t[n] = A() # E: Unsupported target for indexed assignment class A: pass class B: pass -[builtins fixtures/tuple.py] +[builtins fixtures/tuple.pyi] -- Multiple assignment @@ -235,7 +235,7 @@ a, b, a = t2 class A: pass class B: pass -[builtins fixtures/tuple.py] +[builtins fixtures/tuple.pyi] [case testMultipleAssignmentWithInvalidNumberOfValues] from typing import Tuple @@ -248,7 +248,7 @@ a, a, a, a = t1 # E: Need more than 3 values to unpack (4 expected) a, a, a = t1 class A: pass -[builtins fixtures/tuple.py] +[builtins fixtures/tuple.pyi] [case testMultipleAssignmentWithTupleExpressionRvalue] @@ -262,7 +262,7 @@ a, a = a, a class A: pass class B: pass -[builtins fixtures/tuple.py] +[builtins fixtures/tuple.pyi] [out] main:4: error: Incompatible types in assignment (expression has type "A", variable has type "B") main:5: error: Incompatible types in assignment (expression has type "B", variable has type "A") @@ -280,7 +280,7 @@ b, a = b, b class A: pass class B(A): pass -[builtins fixtures/tuple.py] +[builtins fixtures/tuple.pyi] [case testInitializationWithMultipleValues] @@ -296,7 +296,7 @@ ax, bx = a, b # type: (A, B) class A: pass class B: pass -[builtins fixtures/tuple.py] +[builtins fixtures/tuple.pyi] [case testMultipleAssignmentWithNonTupleRvalue] @@ -309,7 +309,7 @@ a, b = f # E: 'def () -> Any' object is not iterable class A: pass class B: pass -[builtins fixtures/tuple.py] +[builtins fixtures/tuple.pyi] [case testMultipleAssignmentWithIndexedLvalues] @@ -329,7 +329,7 @@ class B: class AA: pass class BB: pass -[builtins fixtures/tuple.py] +[builtins fixtures/tuple.pyi] [case testMultipleDeclarationWithParentheses] @@ -356,7 +356,7 @@ a, b = None, None # type: (A, B) class A: pass class B: pass -[builtins fixtures/tuple.py] +[builtins fixtures/tuple.pyi] [case testMultipleAssignmentUsingSingleTupleType] from typing import Tuple @@ -382,7 +382,7 @@ from typing import List t = 1, 2 a, b, *c = 1, 2 # E: Need type annotation for variable aa, bb, *cc = t # E: Need type annotation for variable -[builtins fixtures/list.py] +[builtins fixtures/list.pyi] [case testAssignmentToStarAnnotation] from typing import List @@ -390,7 +390,7 @@ li, lo = None, None # type: List[int], List[object] a, b, *c = 1, 2 # type: int, int, *List[int] c = lo # E: Incompatible types in assignment (expression has type List[object], variable has type List[int]) c = li -[builtins fixtures/list.py] +[builtins fixtures/list.pyi] [case testAssignmentToStarCount1] from typing import List @@ -400,7 +400,7 @@ a, b, *c = 1, # E: Need more than 1 value to unpack (2 expected) a, b, *c = 1, 2 a, b, *c = 1, 2, 3 a, b, *c = 1, 2, 3, 4 -[builtins fixtures/list.py] +[builtins fixtures/list.pyi] [case testAssignmentToStarCount2] from typing import List @@ -414,7 +414,7 @@ a, b, *c = t1 # E: Need more than 1 value to unpack (2 expected) a, b, *c = t2 a, b, *c = t3 a, b, *c = t4 -[builtins fixtures/list.py] +[builtins fixtures/list.pyi] [case testAssignmentToStarFromAny] from typing import Any @@ -432,7 +432,7 @@ a, *(li) = 1, a, *(b, c) = 1, 2 # E: Need more than 1 value to unpack (2 expected) a, *(b, c) = 1, 2, 3 a, *(b, c) = 1, 2, 3, 4 # E: Too many values to unpack (2 expected, 3 provided) -[builtins fixtures/list.py] +[builtins fixtures/list.pyi] [case testAssignmentToStarFromTupleType] from typing import List, Tuple @@ -446,7 +446,7 @@ na = la na = a # E class A: pass -[builtins fixtures/list.py] +[builtins fixtures/list.pyi] [out] main:6: error: List item 0 has incompatible type "A" main:6: error: List item 1 has incompatible type "A" @@ -461,7 +461,7 @@ l = li # E: Incompatible types in assignment (expression has type List[int], va l = la class A: pass -[builtins fixtures/list.py] +[builtins fixtures/list.pyi] [out] [case testAssignmentToStarFromListInference] @@ -473,7 +473,7 @@ l = li # E: Incompatible types in assignment (expression has type List[int], va l = la class A: pass -[builtins fixtures/list.py] +[builtins fixtures/list.pyi] [out] [case testAssignmentToStarFromTupleTypeInference] @@ -486,7 +486,7 @@ l = li # E: Incompatible types in assignment (expression has type List[int], va l = la class A: pass -[builtins fixtures/list.py] +[builtins fixtures/list.pyi] [out] [case testAssignmentToStarFromListTypeInference] @@ -498,7 +498,7 @@ l = li # E: Incompatible types in assignment (expression has type List[int], va l = la class A: pass -[builtins fixtures/list.py] +[builtins fixtures/list.pyi] [out] @@ -568,7 +568,7 @@ def f(x: 'A') -> None: pass class A: def __add__(self, x: 'A') -> 'A': pass -[builtins fixtures/tuple.py] +[builtins fixtures/tuple.pyi] [case testLargeTuplesInErrorMessages] @@ -577,7 +577,7 @@ a + (a, a, a, a, a, a, a) # Fail class LongTypeName: def __add__(self, x: 'LongTypeName') -> 'LongTypeName': pass -[builtins fixtures/tuple.py] +[builtins fixtures/tuple.pyi] [out] main:3: error: Unsupported operand types for + ("LongTypeName" and tuple(length 7)) @@ -628,19 +628,19 @@ t = 1, 2 for x in t: x = 1 x = '' # E: Incompatible types in assignment (expression has type "str", variable has type "int") -[builtins fixtures/for.py] +[builtins fixtures/for.pyi] [case testForLoopOverEmptyTuple] import typing t = () for x in t: pass # E: Need type annotation for variable -[builtins fixtures/for.py] +[builtins fixtures/for.pyi] [case testForLoopOverNoneValuedTuple] import typing t = () for x in None, None: pass # E: Need type annotation for variable -[builtins fixtures/for.py] +[builtins fixtures/for.pyi] [case testForLoopOverTupleAndSubtyping] import typing @@ -650,13 +650,13 @@ for x in B(), A(): x = A() x = B() x = '' # E: Incompatible types in assignment (expression has type "str", variable has type "A") -[builtins fixtures/for.py] +[builtins fixtures/for.pyi] [case testTupleIterable] y = 'a' x = sum((1,2)) y = x # E: Incompatible types in assignment (expression has type "int", variable has type "str") -[builtins fixtures/tuple.py] +[builtins fixtures/tuple.pyi] -- Tuple as a base type @@ -673,7 +673,7 @@ class A(Tuple[int, str]): a, b = self b, a = self # Error self.f('') # Error -[builtins fixtures/tuple.py] +[builtins fixtures/tuple.pyi] [out] main:1: note: In module imported here: tmp/m.pyi: note: In member "f" of class "A": @@ -684,7 +684,7 @@ tmp/m.pyi:7: error: Argument 1 to "f" of "A" has incompatible type "str"; expect [case testInvalidTupleBaseClass] from typing import Tuple class A(Tuple[int, str]): pass # E: Tuple[...] not supported as a base class outside a stub file -[builtins fixtures/tuple.py] +[builtins fixtures/tuple.pyi] [out] [case testValidTupleBaseClass] @@ -710,7 +710,7 @@ from typing import TypeVar, Generic, Tuple T = TypeVar('T') class Test(Generic[T], Tuple[T]): pass x = Test() # type: Test[int] -[builtins fixtures/tuple.py] +[builtins fixtures/tuple.pyi] [out] main:3: error: Tuple[...] not supported as a base class outside a stub file main:4: error: Generic tuple types not supported @@ -726,7 +726,7 @@ x = () # type: Tuple[str, ...] n = 5 x[n]() # E: "str" not callable x[3]() # E: "str" not callable -[builtins fixtures/tuple.py] +[builtins fixtures/tuple.pyi] [case testSubtypingVariableLengthTuple] from typing import Tuple @@ -740,7 +740,7 @@ fa(ta) fa(tb) fb(tb) fb(ta) # E: Argument 1 to "fb" has incompatible type Tuple[A, ...]; expected Tuple[B, ...] -[builtins fixtures/tuple.py] +[builtins fixtures/tuple.pyi] [case testSubtypingFixedAndVariableLengthTuples] from typing import Tuple @@ -757,7 +757,7 @@ fa(bb) fb(bb) fb(ab) # E: Argument 1 to "fb" has incompatible type "Tuple[A, B]"; expected Tuple[B, ...] fb(aa) # E: Argument 1 to "fb" has incompatible type "Tuple[A, A]"; expected Tuple[B, ...] -[builtins fixtures/tuple.py] +[builtins fixtures/tuple.pyi] [case testSubtypingTupleIsContainer] from typing import Container @@ -779,7 +779,7 @@ reveal_type(b) # E: Revealed type is 'Tuple[builtins.int, builtins.int, builtin a = [1] b = (0, *a) reveal_type(b) # E: Revealed type is 'builtins.tuple[builtins.int*]' -[builtins fixtures/tuple.py] +[builtins fixtures/tuple.pyi] [case testTupleWithStarExpr3] a = [''] @@ -787,24 +787,24 @@ b = (0, *a) reveal_type(b) # E: Revealed type is 'builtins.tuple[builtins.object*]' c = (*a, '') reveal_type(c) # E: Revealed type is 'builtins.tuple[builtins.str*]' -[builtins fixtures/tuple.py] +[builtins fixtures/tuple.pyi] [case testTupleWithStarExpr4] a = (1, 1, 'x', 'x') b = (1, 'x') a = (0, *b, '') -[builtins fixtures/tuple.py] +[builtins fixtures/tuple.pyi] [case testTupleWithUndersizedContext] a = ([1], 'x') a = ([], 'x', 1) # E: Incompatible types in assignment (expression has type "Tuple[List[int], str, int]", variable has type "Tuple[List[int], str]") -[builtins fixtures/tuple.py] +[builtins fixtures/tuple.pyi] [case testTupleWithOversizedContext] a = (1, [1], 'x') a = (1, []) # E: Incompatible types in assignment (expression has type "Tuple[int, List[int]]", variable has type "Tuple[int, List[int], str]") -[builtins fixtures/tuple.py] +[builtins fixtures/tuple.pyi] [case testTupleWithoutContext] a = (1, []) # E: Need type annotation for variable -[builtins fixtures/tuple.py] +[builtins fixtures/tuple.pyi] diff --git a/test-data/unit/check-type-aliases.test b/test-data/unit/check-type-aliases.test index b92d270e12e5..f67456ef375e 100644 --- a/test-data/unit/check-type-aliases.test +++ b/test-data/unit/check-type-aliases.test @@ -33,7 +33,7 @@ A = List[int] def f(x: A) -> None: pass f([1]) f(['x']) # E: List item 0 has incompatible type "str" -[builtins fixtures/list.py] +[builtins fixtures/list.pyi] [out] [case testAnyTypeAlias] @@ -54,10 +54,10 @@ f(()) # E: Argument 1 to "f" has incompatible type "Tuple[]"; expected "Union[in [file _m.py] from typing import Union U = Union[int, str] -[builtins fixtures/tuple.py] +[builtins fixtures/tuple.pyi] [case testTypeAliasInBuiltins] def f(x: bytes): pass bytes f(1) # E: Argument 1 to "f" has incompatible type "int"; expected "str" -[builtins fixtures/alias.py] +[builtins fixtures/alias.pyi] diff --git a/test-data/unit/check-type-checks.test b/test-data/unit/check-type-checks.test index e41bd80afb8f..ed37dc4c4dc6 100644 --- a/test-data/unit/check-type-checks.test +++ b/test-data/unit/check-type-checks.test @@ -11,7 +11,7 @@ if isinstance(x, int): n = x s = x # E: Incompatible types in assignment (expression has type "int", variable has type "str") n = x # E: Incompatible types in assignment (expression has type "object", variable has type "int") -[builtins fixtures/isinstance.py] +[builtins fixtures/isinstance.pyi] [case testSimpleIsinstance2] import typing @@ -21,7 +21,7 @@ def f(x: object, n: int, s: str) -> None: n = x s = x # E: Incompatible types in assignment (expression has type "int", variable has type "str") n = x # E: Incompatible types in assignment (expression has type "object", variable has type "int") -[builtins fixtures/isinstance.py] +[builtins fixtures/isinstance.pyi] [out] main: note: In function "f": @@ -37,7 +37,7 @@ class A: s = x # E: Incompatible types in assignment (expression has type "int", variable has type "str") else: n = x # E: Incompatible types in assignment (expression has type "object", variable has type "int") -[builtins fixtures/isinstance.py] +[builtins fixtures/isinstance.pyi] [out] main: note: In class "A": @@ -52,7 +52,7 @@ def f(x: object, a: A, b: B, c: int) -> None: x = a a = x c = x # E: Incompatible types in assignment (expression has type "A", variable has type "int") -[builtins fixtures/isinstance.py] +[builtins fixtures/isinstance.pyi] [out] main: note: In function "f": @@ -70,7 +70,7 @@ def f(x: object, y: object, n: int, s: str) -> None: s = y # E: Incompatible types in assignment (expression has type "object", variable has type "str") n = y # E: Incompatible types in assignment (expression has type "object", variable has type "int") n = x -[builtins fixtures/isinstance.py] +[builtins fixtures/isinstance.pyi] [out] main: note: In function "f": @@ -88,7 +88,7 @@ def f(x: object, n: int, s: str) -> None: n = x # E: Incompatible types in assignment (expression has type "object", variable has type "int") s = x # E: Incompatible types in assignment (expression has type "object", variable has type "str") n = x # E: Incompatible types in assignment (expression has type "object", variable has type "int") -[builtins fixtures/isinstance.py] +[builtins fixtures/isinstance.pyi] [out] main: note: In function "f": @@ -100,7 +100,7 @@ def f(x: Any, n: int, s: str) -> None: n = x s = x # E: Incompatible types in assignment (expression has type "int", variable has type "str") s = x -[builtins fixtures/isinstance.py] +[builtins fixtures/isinstance.pyi] [out] main: note: In function "f": @@ -115,6 +115,6 @@ def f(x: object) -> None: x.f('') x.g() # E: C[Any] has no attribute "g" x.g() # E: "object" has no attribute "g" -[builtins fixtures/isinstance.py] +[builtins fixtures/isinstance.pyi] [out] main: note: In function "f": diff --git a/test-data/unit/check-type-promotion.test b/test-data/unit/check-type-promotion.test index d3482dabaf2c..0a3999662041 100644 --- a/test-data/unit/check-type-promotion.test +++ b/test-data/unit/check-type-promotion.test @@ -4,36 +4,36 @@ [case testPromoteIntToFloat] def f(x: float) -> None: pass f(1) -[builtins fixtures/primitives.py] +[builtins fixtures/primitives.pyi] [case testCantPromoteFloatToInt] def f(x: int) -> None: pass f(1.1) # E: Argument 1 to "f" has incompatible type "float"; expected "int" -[builtins fixtures/primitives.py] +[builtins fixtures/primitives.pyi] [case testPromoteFloatToComplex] def f(x: complex) -> None: pass f(1) -[builtins fixtures/primitives.py] +[builtins fixtures/primitives.pyi] [case testPromoteIntToComplex] def f(x: complex) -> None: pass f(1) -[builtins fixtures/primitives.py] +[builtins fixtures/primitives.pyi] [case testPromoteBytearrayToByte] def f(x: bytes) -> None: pass f(bytearray()) -[builtins fixtures/primitives.py] +[builtins fixtures/primitives.pyi] [case testNarrowingDownFromPromoteTargetType] y = 0.0 y = 1 y() # E: "int" not callable -[builtins fixtures/primitives.py] +[builtins fixtures/primitives.pyi] [case testNarrowingDownFromPromoteTargetType2] y = 0.0 y = 1 y.x # E: "int" has no attribute "x" -[builtins fixtures/primitives.py] +[builtins fixtures/primitives.pyi] diff --git a/test-data/unit/check-typevar-values.test b/test-data/unit/check-typevar-values.test index 435c77cdc435..b165c25fe638 100644 --- a/test-data/unit/check-typevar-values.test +++ b/test-data/unit/check-typevar-values.test @@ -19,7 +19,7 @@ o = [object()] i = f(1) s = f('') o = f(1) # E: Type argument 1 of "f" has incompatible value "object" -[builtins fixtures/list.py] +[builtins fixtures/list.pyi] [case testCallGenericFunctionWithTypeVarValueRestrictionAndAnyArgs] from typing import TypeVar, Any @@ -118,7 +118,7 @@ def h(x: T) -> T: if isinstance(x, int): return '' # E: Incompatible return value type (got "str", expected "int") return x -[builtins fixtures/isinstance.py] +[builtins fixtures/isinstance.pyi] [out] main: note: In function "h": @@ -136,7 +136,7 @@ def g(x: T) -> T: else: return 2 # E: Incompatible return value type (got "int", expected "str") return x -[builtins fixtures/isinstance.py] +[builtins fixtures/isinstance.pyi] [out] main: note: In function "g": @@ -149,7 +149,7 @@ def f(x: T) -> T: else: y = '' return y -[builtins fixtures/isinstance.py] +[builtins fixtures/isinstance.pyi] [case testIsinstanceAndTypeVarValues4] from typing import TypeVar @@ -160,7 +160,7 @@ def f(x: T) -> T: else: y = object() return y # E: Incompatible return value type (got "object", expected "str") -[builtins fixtures/isinstance.py] +[builtins fixtures/isinstance.pyi] [out] main: note: In function "f": @@ -173,7 +173,7 @@ def f(x: T) -> T: else: y = '' return y # E: Incompatible return value type (got "object", expected "int") -[builtins fixtures/isinstance.py] +[builtins fixtures/isinstance.pyi] [out] main: note: In function "f": @@ -197,7 +197,7 @@ def g(x: S) -> None: y = x if isinstance(x, int): x = y -[builtins fixtures/isinstance.py] +[builtins fixtures/isinstance.pyi] [out] main: note: In function "f": @@ -216,7 +216,7 @@ def f(x: T) -> None: x = y x = 1 x = S() # E: Incompatible types in assignment (expression has type "S", variable has type "int") -[builtins fixtures/isinstance.py] +[builtins fixtures/isinstance.pyi] [out] main: note: In function "f": diff --git a/test-data/unit/check-unions.test b/test-data/unit/check-unions.test index 81b7d4451877..121413836014 100644 --- a/test-data/unit/check-unions.test +++ b/test-data/unit/check-unions.test @@ -9,7 +9,7 @@ def f(x: Union[int, str]) -> None: elif isinstance(x, str): z = 'a' z = x -[builtins fixtures/isinstance.py] +[builtins fixtures/isinstance.pyi] [case testUnion2] from typing import Union @@ -20,7 +20,7 @@ def f(x: Union[int, str]) -> None: else: z = 'a' z = x -[builtins fixtures/isinstance.py] +[builtins fixtures/isinstance.pyi] [case testUnion3] from typing import Union @@ -31,7 +31,7 @@ def f(x: Union[int, str]) -> None: else: z = 2 z = x # E: Incompatible types in assignment (expression has type "str", variable has type "int") -[builtins fixtures/isinstance.py] +[builtins fixtures/isinstance.pyi] [out] main: note: In function "f": @@ -54,7 +54,7 @@ w.y = 'a' # E: Incompatible types in assignment (expression has type "str", y = x.y # E: Some element of union has no attribute "y" z = x.y # E: Some element of union has no attribute "y" -[builtins fixtures/isinstance.py] +[builtins fixtures/isinstance.pyi] [case testUnionMethodCalls] from typing import Union @@ -75,14 +75,14 @@ y.foo() i = x.foo() i = y.foo() # E: Incompatible types in assignment (expression has type "Union[int, str]", variable has type "int") -[builtins fixtures/isinstance.py] +[builtins fixtures/isinstance.pyi] [case testUnionIndexing] from typing import Union, List x = None # type: Union[List[int], str] x[2] x[2] + 1 # E: Unsupported operand types for + (likely involving Union) -[builtins fixtures/isinstancelist.py] +[builtins fixtures/isinstancelist.pyi] [case testUnionAsOverloadArg] from typing import Union, overload @@ -118,7 +118,7 @@ def f(x: List[T]) -> Union[T, int]: pass def g(y: str) -> None: pass a = f([1]) g(a) # E: Argument 1 to "g" has incompatible type "int"; expected "str" -[builtins fixtures/list.py] +[builtins fixtures/list.pyi] [case testUnionSimplificationGenericClass] from typing import TypeVar, Union, Generic diff --git a/test-data/unit/check-unreachable-code.test b/test-data/unit/check-unreachable-code.test index 1668aeae8713..54c1fe58b619 100644 --- a/test-data/unit/check-unreachable-code.test +++ b/test-data/unit/check-unreachable-code.test @@ -76,7 +76,7 @@ if not MYPY: import xyz753 else: import pow123 # E -[builtins fixtures/bool.py] +[builtins fixtures/bool.pyi] [out] main:6: error: Cannot find module named 'pow123' main:6: note: (Perhaps setting MYPYPATH or using the "--silent-imports" flag would help) @@ -88,7 +88,7 @@ if MYPY: None + 1 # E: Unsupported left operand type for + (None) else: None + '' -[builtins fixtures/bool.py] +[builtins fixtures/bool.pyi] [case testConditionalClassDefPY3] def f(): pass @@ -119,7 +119,7 @@ if sys.version_info[0] >= 3: else: def foo() -> str: return '' reveal_type(foo()) # E: Revealed type is 'builtins.str' -[builtins_py2 fixtures/ops.py] +[builtins_py2 fixtures/ops.pyi] [out] [case testSysVersionInfo] @@ -129,7 +129,7 @@ if sys.version_info[0] >= 3: else: def foo() -> str: return '' reveal_type(foo()) # E: Revealed type is 'builtins.int' -[builtins fixtures/ops.py] +[builtins fixtures/ops.pyi] [out] [case testSysVersionInfoNegated_python2] @@ -139,7 +139,7 @@ if not (sys.version_info[0] < 3): else: def foo() -> str: return '' reveal_type(foo()) # E: Revealed type is 'builtins.str' -[builtins_py2 fixtures/ops.py] +[builtins_py2 fixtures/ops.pyi] [out] [case testSysVersionInfoNegated] @@ -149,7 +149,7 @@ if not (sys.version_info[0] < 3): else: def foo() -> str: return '' reveal_type(foo()) # E: Revealed type is 'builtins.int' -[builtins fixtures/ops.py] +[builtins fixtures/ops.pyi] [out] [case testSysVersionInfoSliced1] @@ -159,7 +159,7 @@ if sys.version_info[:1] >= (3,): else: def foo() -> str: return '' foo() + 0 -[builtins fixtures/ops.py] +[builtins fixtures/ops.pyi] [out] [case testSysVersionInfoSliced2] @@ -169,7 +169,7 @@ if sys.version_info[:2] >= (3, 0): else: def foo() -> str: return '' foo() + 0 -[builtins fixtures/ops.py] +[builtins fixtures/ops.pyi] [out] [case testSysVersionInfoSliced3] @@ -179,7 +179,7 @@ if sys.version_info[:] >= (3, 0): else: def foo() -> str: return '' foo() + 0 -[builtins fixtures/ops.py] +[builtins fixtures/ops.pyi] [out] [case testSysVersionInfoSliced4] @@ -189,7 +189,7 @@ if sys.version_info[0:2] >= (3, 0): else: def foo() -> str: return '' foo() + 0 -[builtins fixtures/ops.py] +[builtins fixtures/ops.pyi] [out] [case testSysVersionInfoSliced5] @@ -199,7 +199,7 @@ if sys.version_info[0:] >= (3,): else: def foo() -> str: return '' foo() + 0 -[builtins fixtures/ops.py] +[builtins fixtures/ops.pyi] [out] [case testSysVersionInfoSliced6] @@ -209,7 +209,7 @@ if sys.version_info[1:] >= (5,): else: def foo() -> str: return '' foo() + 0 -[builtins fixtures/ops.py] +[builtins fixtures/ops.pyi] [out] [case testSysVersionInfoSliced7] @@ -219,7 +219,7 @@ if sys.version_info >= (3, 5): else: def foo() -> str: return '' foo() + 0 -[builtins fixtures/ops.py] +[builtins fixtures/ops.pyi] [out] [case testSysVersionInfoSliced8] @@ -230,7 +230,7 @@ if sys.version_info >= (3, 5, 0): def foo() -> int: return 0 else: def foo() -> str: return '' # E: All conditional function variants must have identical signatures -[builtins fixtures/ops.py] +[builtins fixtures/ops.pyi] [out] [case testSysVersionInfoSliced9] @@ -241,7 +241,7 @@ if sys.version_info[1:] >= (5, 0): def foo() -> int: return 0 else: def foo() -> str: return '' # E: All conditional function variants must have identical signatures -[builtins fixtures/ops.py] +[builtins fixtures/ops.pyi] [out] [case testSysPlatform1] @@ -251,7 +251,7 @@ if sys.platform == 'fictional': else: def foo() -> str: return '' foo() + '' -[builtins fixtures/ops.py] +[builtins fixtures/ops.pyi] [out] [case testSysPlatform2] @@ -261,7 +261,7 @@ if sys.platform != 'fictional': else: def foo() -> str: return '' foo() + 0 -[builtins fixtures/ops.py] +[builtins fixtures/ops.pyi] [out] [case testSysPlatformNegated] @@ -271,7 +271,7 @@ if not (sys.platform == 'fictional'): else: def foo() -> str: return '' foo() + 0 -[builtins fixtures/ops.py] +[builtins fixtures/ops.pyi] [out] [case testSysVersionInfoClass] @@ -283,7 +283,7 @@ else: class C: def foo(self) -> int: return 0 C().foo() + 0 -[builtins fixtures/ops.py] +[builtins fixtures/ops.pyi] [out] [case testSysVersionInfoImport] @@ -293,7 +293,7 @@ if sys.version_info >= (3, 5): else: collections = None Pt = collections.namedtuple('Pt', 'x y z') -[builtins fixtures/ops.py] +[builtins fixtures/ops.pyi] [out] [case testSysVersionInfoVariable] @@ -303,7 +303,7 @@ if sys.version_info >= (3, 5): else: x = 0 x + '' -[builtins fixtures/ops.py] +[builtins fixtures/ops.pyi] [out] [case testSysVersionInfoInClass] @@ -314,7 +314,7 @@ class C: else: def foo(self) -> str: return '' reveal_type(C().foo()) # E: Revealed type is 'builtins.int' -[builtins fixtures/ops.py] +[builtins fixtures/ops.pyi] [out] [case testSysVersionInfoInFunction] @@ -325,7 +325,7 @@ def foo() -> None: else: x = 0 reveal_type(x) # E: Revealed type is 'builtins.str' -[builtins fixtures/ops.py] +[builtins fixtures/ops.pyi] [out] main: note: In function "foo": @@ -338,6 +338,6 @@ class C: else: x = 0 reveal_type(x) # E: Revealed type is 'builtins.str' -[builtins fixtures/ops.py] +[builtins fixtures/ops.pyi] [out] main: note: In member "foo" of class "C": diff --git a/test-data/unit/check-varargs.test b/test-data/unit/check-varargs.test index 9def84aab33f..eaf40b9599f0 100644 --- a/test-data/unit/check-varargs.test +++ b/test-data/unit/check-varargs.test @@ -17,7 +17,7 @@ def f( *b: 'B') -> None: class B: pass class C: pass -[builtins fixtures/tuple.py] +[builtins fixtures/tuple.pyi] [out] main: note: In function "f": @@ -29,7 +29,7 @@ def want_sequence(types: Sequence[type]): pass def test(*t: type) -> None: want_tuple(t) want_sequence(t) -[builtins fixtures/tuple.py] +[builtins fixtures/tuple.pyi] [out] @@ -59,7 +59,7 @@ def g() -> None: pass class A: pass class B(A): pass class C: pass -[builtins fixtures/list.py] +[builtins fixtures/list.pyi] [case testCallingVarArgsFunctionWithAlsoNormalArgs] @@ -79,7 +79,7 @@ def f(a: 'C', *b: 'A') -> None: pass class A: pass class B(A): pass class C: pass -[builtins fixtures/list.py] +[builtins fixtures/list.pyi] [case testCallingVarArgsFunctionWithDefaultArgs] @@ -101,7 +101,7 @@ def f(a: 'C' = None, *b: 'A') -> None: class A: pass class B(A): pass class C: pass -[builtins fixtures/list.py] +[builtins fixtures/list.pyi] [case testCallVarargsFunctionWithIterable] from typing import Iterable @@ -110,7 +110,7 @@ it2 = None # type: Iterable[str] def f(*x: int) -> None: pass f(*it1) f(*it2) # E: Argument 1 to "f" has incompatible type *Iterable[str]; expected "int" -[builtins fixtures/for.py] +[builtins fixtures/for.pyi] [case testCallVarargsFunctionWithIterableAndPositional] # options: fast_parser @@ -120,7 +120,7 @@ def f(*x: int) -> None: pass f(*it1, 1, 2) f(*it1, 1, *it1, 2) f(*it1, '') # E: Argument 2 to "f" has incompatible type "str"; expected "int" -[builtins fixtures/for.py] +[builtins fixtures/for.pyi] [case testCallVarargsFunctionWithTupleAndPositional] # options: fast_parser @@ -129,7 +129,7 @@ it1 = (1, 2) f(*it1, 1, 2) f(*it1, 1, *it1, 2) f(*it1, '') # E: Argument 2 to "f" has incompatible type "str"; expected "int" -[builtins fixtures/for.py] +[builtins fixtures/for.pyi] -- Calling varargs function + type inference @@ -161,7 +161,7 @@ def f( *a: T) -> T: class A: pass class B(A): pass class C: pass -[builtins fixtures/list.py] +[builtins fixtures/list.pyi] [case testTypeInferenceWithCalleeVarArgsAndDefaultArgs] from typing import TypeVar @@ -182,7 +182,7 @@ def f(a: T, b: T = None, *c: T) -> T: pass class A: pass -[builtins fixtures/list.py] +[builtins fixtures/list.pyi] -- Calling normal function with varargs @@ -207,7 +207,7 @@ def f(a: 'A', b: 'B') -> None: class A: pass class B: pass -[builtins fixtures/list.py] +[builtins fixtures/list.pyi] [out] main:7: error: Argument 1 to "f" has incompatible type *List[A]; expected "B" @@ -236,7 +236,7 @@ class A: pass class B: pass class C: pass class CC(C): pass -[builtins fixtures/tuple.py] +[builtins fixtures/tuple.pyi] [case testInvalidVarArg] @@ -250,7 +250,7 @@ def f(a: 'A') -> None: pass class A: pass -[builtins fixtures/tuple.py] +[builtins fixtures/tuple.pyi] -- Calling varargs function with varargs @@ -276,7 +276,7 @@ def f(a: 'A', *b: 'B') -> None: pass def g(a: 'A', *b: 'A') -> None: pass class A: pass class B: pass -[builtins fixtures/list.py] +[builtins fixtures/list.pyi] [out] main:3: error: Argument 1 to "f" has incompatible type *List[A]; expected "B" main:4: error: Argument 2 to "f" has incompatible type *List[A]; expected "B" @@ -310,7 +310,7 @@ class A: pass class B: pass class C: pass class CC(C): pass -[builtins fixtures/list.py] +[builtins fixtures/list.pyi] -- Varargs special cases @@ -331,7 +331,7 @@ g(a, a, *d) def f(a: 'A') -> None: pass def g(a: 'A', *b: 'A') -> None: pass class A: pass -[builtins fixtures/list.py] +[builtins fixtures/list.pyi] [out] main:3: error: Too many arguments for "f" main:4: error: Too many arguments for "f" @@ -354,7 +354,7 @@ def g( *a: 'B') -> None: class A: pass class B(A): pass -[builtins fixtures/list.py] +[builtins fixtures/list.pyi] [case testCallerVarArgsAndDefaultArgs] @@ -375,7 +375,7 @@ def f(a: 'A', b: 'B' = None, *c: 'B') -> None: class A: pass class B: pass -[builtins fixtures/list.py] +[builtins fixtures/list.pyi] [out] main:3: error: Too few arguments for "f" main:4: error: Argument 2 to "f" has incompatible type *List[A]; expected "B" @@ -385,7 +385,7 @@ main:6: error: Argument 1 to "f" has incompatible type *"Tuple[A, A, B]"; expect [case testVarArgsAfterKeywordArgInCall1] def f(x: int, y: str) -> None: pass f(x=1, *[2]) -[builtins fixtures/list.py] +[builtins fixtures/list.pyi] [out] main:2: error: "f" gets multiple values for keyword argument "x" main:2: error: Argument 2 to "f" has incompatible type *List[int]; expected "str" @@ -393,7 +393,7 @@ main:2: error: Argument 2 to "f" has incompatible type *List[int]; expected "str [case testVarArgsAfterKeywordArgInCall2] def f(x: int, y: str) -> None: pass f(y='x', *[1]) -[builtins fixtures/list.py] +[builtins fixtures/list.pyi] [out] main:2: error: "f" gets multiple values for keyword argument "y" main:2: error: Argument 2 to "f" has incompatible type *List[int]; expected "str" @@ -401,17 +401,17 @@ main:2: error: Argument 2 to "f" has incompatible type *List[int]; expected "str [case testVarArgsAfterKeywordArgInCall3] def f(x: int, y: str) -> None: pass f(y='x', *(1,)) -[builtins fixtures/list.py] +[builtins fixtures/list.pyi] [case testVarArgsAfterKeywordArgInCall4] def f(x: int, *, y: str) -> None: pass f(y='x', *[1]) -[builtins fixtures/list.py] +[builtins fixtures/list.pyi] [case testVarArgsAfterKeywordArgInCall5] def f(x: int, *, y: str) -> None: pass f(y='x', *(1,)) -[builtins fixtures/list.py] +[builtins fixtures/list.pyi] -- Overloads + varargs @@ -456,7 +456,7 @@ def f(a: A = None, *b: B) -> A: pass @overload def f(a: B, *b: B) -> B: pass -[builtins fixtures/list.py] +[builtins fixtures/list.pyi] -- Caller varargs + type inference @@ -486,7 +486,7 @@ def f(a: S, *b: T) -> Tuple[S, T]: class A: pass class B: pass -[builtins fixtures/list.py] +[builtins fixtures/list.pyi] [out] main:6: error: Argument 1 to "f" has incompatible type *List[A]; expected "B" main:7: error: Argument 1 to "f" has incompatible type *List[A]; expected "B" @@ -515,7 +515,7 @@ def f(a: S, b: T) -> Tuple[S, T]: pass class A: pass class B: pass -[builtins fixtures/list.py] +[builtins fixtures/list.pyi] [case testCallerVarargsAndComplexTypeInference] from typing import List, TypeVar, Generic, Tuple @@ -539,7 +539,7 @@ class G(Generic[T]): class A: pass class B: pass -[builtins fixtures/list.py] +[builtins fixtures/list.pyi] [out] main:9: error: Incompatible types in assignment (expression has type List[A], variable has type "A") main:9: error: Incompatible types in assignment (expression has type List[None], variable has type List[A]) @@ -560,7 +560,7 @@ f(1) f(1, 2) f('') # E: Argument 1 to "f" has incompatible type "str"; expected "int" f(1, '') # E: Argument 2 to "f" has incompatible type "str"; expected "int" -[builtins fixtures/list.py] +[builtins fixtures/list.pyi] -- Subtyping @@ -574,7 +574,7 @@ def f(*x: int) -> None: pass def g(*x: str) -> None: pass x = f x = g # E: Incompatible types in assignment (expression has type Callable[[str], None], variable has type Callable[[int], None]) -[builtins fixtures/list.py] +[builtins fixtures/list.pyi] [out] diff --git a/test-data/unit/check-warnings.test b/test-data/unit/check-warnings.test index 54486aa641ee..af2ecbfe7931 100644 --- a/test-data/unit/check-warnings.test +++ b/test-data/unit/check-warnings.test @@ -18,7 +18,7 @@ from typing import cast, Union x = 1 # type: Union[int, str] if isinstance(x, str): cast(str, x) -[builtins fixtures/isinstance.py] +[builtins fixtures/isinstance.pyi] [out] main:5: note: Redundant cast to "str" @@ -33,7 +33,7 @@ a = A() b = B() # Without the cast, the following line would fail to type check. c = add([cast(A, b)], [a]) -[builtins fixtures/list.py] +[builtins fixtures/list.pyi] -- Unused 'type: ignore' comments diff --git a/test-data/unit/check-weak-typing.test b/test-data/unit/check-weak-typing.test index 8aa14db53b99..0bb94d96d293 100644 --- a/test-data/unit/check-weak-typing.test +++ b/test-data/unit/check-weak-typing.test @@ -2,7 +2,7 @@ x = 17 y = [] # E: Need type annotation for variable z = [2] -[builtins fixtures/list.py] +[builtins fixtures/list.pyi] [out] [case testWeakLocalNotGlobal] @@ -10,7 +10,7 @@ z = [2] y = [] # E: Need type annotation for variable x = 1 x = 'a' # E: Incompatible types in assignment (expression has type "str", variable has type "int") -[builtins fixtures/list.py] +[builtins fixtures/list.pyi] [out] [case testWeakMoo] @@ -18,7 +18,7 @@ x = 'a' # E: Incompatible types in assignment (expression has type "str", variab x = 7 x + 'd' # E: Unsupported operand types for + ("int" and "str") -[builtins fixtures/ops.py] +[builtins fixtures/ops.pyi] [case testWeakGlobal] # mypy: weak=global @@ -29,7 +29,7 @@ x = 'a' x() # E: "str" not callable x = [1] x[0]() -[builtins fixtures/list.py] +[builtins fixtures/list.pyi] [out] [case testWeakTypingList] @@ -37,7 +37,7 @@ x[0]() x = 17 y = [] z = [2] -[builtins fixtures/list.py] +[builtins fixtures/list.pyi] [out] [case testWeakTypingRename] @@ -45,7 +45,7 @@ z = [2] x = 1 x = 'a' -[builtins fixtures/list.py] +[builtins fixtures/list.pyi] [out] [case testWeakFunctionCall] @@ -73,7 +73,7 @@ def f(): x[0] + 1 x[0] + 'a' x.add('a') # E: List[Any] has no attribute "add"; maybe "append" or "extend"? -[builtins fixtures/list.py] +[builtins fixtures/list.pyi] [out] main: note: In function "f": [case testWeakAssignmentInFunction] @@ -96,7 +96,7 @@ main: note: In function "f": # mypy: weak def f() -> None: x = [] # E: Need type annotation for variable -[builtins fixtures/list.py] +[builtins fixtures/list.pyi] [out] main: note: In function "f": @@ -106,7 +106,7 @@ def f(): x, y = g() # E: 'builtins.int' object is not iterable def g() -> int: return 0 -[builtins fixtures/for.py] +[builtins fixtures/for.pyi] [out] main: note: In function "f": @@ -160,7 +160,7 @@ x + 'a' # E: Unsupported operand types for + ("int" and "str") x = 'a' x + 1 # E: Unsupported operand types for + ("str" and "int") x + 'a' -[builtins fixtures/ops.py] +[builtins fixtures/ops.pyi] [case testWeakConditionalChanges] # mypy: weak @@ -184,7 +184,7 @@ def g(): if 1: return x + 'a' -[builtins fixtures/ops.py] +[builtins fixtures/ops.pyi] [out] main: note: In function "f": [case testWeakListInFunction2] @@ -192,7 +192,7 @@ main: note: In function "f": x = [1] # XXX: not clear what the right result here is x[0]() # E: "int" not callable -[builtins fixtures/list.py] +[builtins fixtures/list.pyi] [case testWeakArgsKws] # mypy: weak=global @@ -206,7 +206,7 @@ args = (1, 2) f(*args, y=2) # E: "f" gets multiple values for keyword argument "y" args = (1,) f(*args, y=2) -[builtins fixtures/dict.py] +[builtins fixtures/dict.pyi] [out] [case testWeakBinder] # mypy: weak=global diff --git a/test-data/unit/fixtures/__new__.py b/test-data/unit/fixtures/__new__.pyi similarity index 100% rename from test-data/unit/fixtures/__new__.py rename to test-data/unit/fixtures/__new__.pyi diff --git a/test-data/unit/fixtures/alias.py b/test-data/unit/fixtures/alias.pyi similarity index 100% rename from test-data/unit/fixtures/alias.py rename to test-data/unit/fixtures/alias.pyi diff --git a/test-data/unit/fixtures/args.py b/test-data/unit/fixtures/args.pyi similarity index 100% rename from test-data/unit/fixtures/args.py rename to test-data/unit/fixtures/args.pyi diff --git a/test-data/unit/fixtures/async_await.py b/test-data/unit/fixtures/async_await.pyi similarity index 100% rename from test-data/unit/fixtures/async_await.py rename to test-data/unit/fixtures/async_await.pyi diff --git a/test-data/unit/fixtures/bool.py b/test-data/unit/fixtures/bool.pyi similarity index 100% rename from test-data/unit/fixtures/bool.py rename to test-data/unit/fixtures/bool.pyi diff --git a/test-data/unit/fixtures/classmethod.py b/test-data/unit/fixtures/classmethod.pyi similarity index 100% rename from test-data/unit/fixtures/classmethod.py rename to test-data/unit/fixtures/classmethod.pyi diff --git a/test-data/unit/fixtures/complex.py b/test-data/unit/fixtures/complex.pyi similarity index 100% rename from test-data/unit/fixtures/complex.py rename to test-data/unit/fixtures/complex.pyi diff --git a/test-data/unit/fixtures/dict.py b/test-data/unit/fixtures/dict.pyi similarity index 100% rename from test-data/unit/fixtures/dict.py rename to test-data/unit/fixtures/dict.pyi diff --git a/test-data/unit/fixtures/exception.py b/test-data/unit/fixtures/exception.pyi similarity index 100% rename from test-data/unit/fixtures/exception.py rename to test-data/unit/fixtures/exception.pyi diff --git a/test-data/unit/fixtures/for.py b/test-data/unit/fixtures/for.pyi similarity index 100% rename from test-data/unit/fixtures/for.py rename to test-data/unit/fixtures/for.pyi diff --git a/test-data/unit/fixtures/function.py b/test-data/unit/fixtures/function.pyi similarity index 100% rename from test-data/unit/fixtures/function.py rename to test-data/unit/fixtures/function.pyi diff --git a/test-data/unit/fixtures/isinstance.py b/test-data/unit/fixtures/isinstance.pyi similarity index 100% rename from test-data/unit/fixtures/isinstance.py rename to test-data/unit/fixtures/isinstance.pyi diff --git a/test-data/unit/fixtures/isinstancelist.py b/test-data/unit/fixtures/isinstancelist.pyi similarity index 63% rename from test-data/unit/fixtures/isinstancelist.py rename to test-data/unit/fixtures/isinstancelist.pyi index 99b0c209b89c..4b3569875ab9 100644 --- a/test-data/unit/fixtures/isinstancelist.py +++ b/test-data/unit/fixtures/isinstancelist.pyi @@ -1,4 +1,4 @@ -from typing import builtinclass, Iterable, Iterator, Generic, TypeVar, List +from typing import builtinclass, Iterable, Iterator, Generic, TypeVar, List, Mapping, overload, Tuple @builtinclass class object: @@ -24,6 +24,8 @@ def __add__(self, x: str) -> str: pass def __getitem__(self, x: int) -> str: pass T = TypeVar('T') +KT = TypeVar('KT') +VT = TypeVar('VT') class list(Iterable[T], Generic[T]): def __iter__(self) -> Iterator[T]: pass @@ -31,3 +33,12 @@ def __mul__(self, x: int) -> list[T]: pass def __setitem__(self, x: int, v: T) -> None: pass def __getitem__(self, x: int) -> T: pass def __add__(self, x: List[T]) -> T: pass + +class dict(Iterable[KT], Mapping[KT, VT], Generic[KT, VT]): + @overload + def __init__(self, **kwargs: VT) -> None: pass + @overload + def __init__(self, arg: Iterable[Tuple[KT, VT]], **kwargs: VT) -> None: pass + def __setitem__(self, k: KT, v: VT) -> None: pass + def __iter__(self) -> Iterator[KT]: pass + def update(self, a: Mapping[KT, VT]) -> None: pass diff --git a/test-data/unit/fixtures/list.py b/test-data/unit/fixtures/list.pyi similarity index 100% rename from test-data/unit/fixtures/list.py rename to test-data/unit/fixtures/list.pyi diff --git a/test-data/unit/fixtures/module.py b/test-data/unit/fixtures/module.pyi similarity index 100% rename from test-data/unit/fixtures/module.py rename to test-data/unit/fixtures/module.pyi diff --git a/test-data/unit/fixtures/module_all.py b/test-data/unit/fixtures/module_all.pyi similarity index 100% rename from test-data/unit/fixtures/module_all.py rename to test-data/unit/fixtures/module_all.pyi diff --git a/test-data/unit/fixtures/ops.py b/test-data/unit/fixtures/ops.pyi similarity index 100% rename from test-data/unit/fixtures/ops.py rename to test-data/unit/fixtures/ops.pyi diff --git a/test-data/unit/fixtures/primitives.py b/test-data/unit/fixtures/primitives.pyi similarity index 100% rename from test-data/unit/fixtures/primitives.py rename to test-data/unit/fixtures/primitives.pyi diff --git a/test-data/unit/fixtures/property.py b/test-data/unit/fixtures/property.pyi similarity index 100% rename from test-data/unit/fixtures/property.py rename to test-data/unit/fixtures/property.pyi diff --git a/test-data/unit/fixtures/python2.py b/test-data/unit/fixtures/python2.pyi similarity index 100% rename from test-data/unit/fixtures/python2.py rename to test-data/unit/fixtures/python2.pyi diff --git a/test-data/unit/fixtures/set.py b/test-data/unit/fixtures/set.pyi similarity index 100% rename from test-data/unit/fixtures/set.py rename to test-data/unit/fixtures/set.pyi diff --git a/test-data/unit/fixtures/slice.py b/test-data/unit/fixtures/slice.pyi similarity index 100% rename from test-data/unit/fixtures/slice.py rename to test-data/unit/fixtures/slice.pyi diff --git a/test-data/unit/fixtures/staticmethod.py b/test-data/unit/fixtures/staticmethod.pyi similarity index 100% rename from test-data/unit/fixtures/staticmethod.py rename to test-data/unit/fixtures/staticmethod.pyi diff --git a/test-data/unit/fixtures/transform.py b/test-data/unit/fixtures/transform.pyi similarity index 100% rename from test-data/unit/fixtures/transform.py rename to test-data/unit/fixtures/transform.pyi diff --git a/test-data/unit/fixtures/tuple-simple.py b/test-data/unit/fixtures/tuple-simple.pyi similarity index 100% rename from test-data/unit/fixtures/tuple-simple.py rename to test-data/unit/fixtures/tuple-simple.pyi diff --git a/test-data/unit/fixtures/tuple.py b/test-data/unit/fixtures/tuple.pyi similarity index 100% rename from test-data/unit/fixtures/tuple.py rename to test-data/unit/fixtures/tuple.pyi diff --git a/test-data/unit/fixtures/union.py b/test-data/unit/fixtures/union.pyi similarity index 100% rename from test-data/unit/fixtures/union.py rename to test-data/unit/fixtures/union.pyi diff --git a/test-data/unit/lib-stub/__builtin__.py b/test-data/unit/lib-stub/__builtin__.pyi similarity index 100% rename from test-data/unit/lib-stub/__builtin__.py rename to test-data/unit/lib-stub/__builtin__.pyi diff --git a/test-data/unit/lib-stub/abc.py b/test-data/unit/lib-stub/abc.pyi similarity index 100% rename from test-data/unit/lib-stub/abc.py rename to test-data/unit/lib-stub/abc.pyi diff --git a/test-data/unit/lib-stub/builtins.py b/test-data/unit/lib-stub/builtins.pyi similarity index 100% rename from test-data/unit/lib-stub/builtins.py rename to test-data/unit/lib-stub/builtins.pyi diff --git a/test-data/unit/lib-stub/collections.py b/test-data/unit/lib-stub/collections.pyi similarity index 100% rename from test-data/unit/lib-stub/collections.py rename to test-data/unit/lib-stub/collections.pyi diff --git a/test-data/unit/lib-stub/sys.py b/test-data/unit/lib-stub/sys.pyi similarity index 100% rename from test-data/unit/lib-stub/sys.py rename to test-data/unit/lib-stub/sys.pyi diff --git a/test-data/unit/lib-stub/types.py b/test-data/unit/lib-stub/types.pyi similarity index 100% rename from test-data/unit/lib-stub/types.py rename to test-data/unit/lib-stub/types.pyi diff --git a/test-data/unit/lib-stub/typing.py b/test-data/unit/lib-stub/typing.pyi similarity index 100% rename from test-data/unit/lib-stub/typing.py rename to test-data/unit/lib-stub/typing.pyi diff --git a/test-data/unit/semanal-classes.test b/test-data/unit/semanal-classes.test index 43b1dc4c3a82..5d04ef6818c5 100644 --- a/test-data/unit/semanal-classes.test +++ b/test-data/unit/semanal-classes.test @@ -408,7 +408,7 @@ MypyFile:1( class A: @staticmethod def f(z: int) -> str: pass -[builtins fixtures/staticmethod.py] +[builtins fixtures/staticmethod.pyi] [out] MypyFile:1( ClassDef:1( @@ -428,7 +428,7 @@ MypyFile:1( class A: @staticmethod def f() -> str: pass -[builtins fixtures/staticmethod.py] +[builtins fixtures/staticmethod.pyi] [out] MypyFile:1( ClassDef:1( @@ -446,7 +446,7 @@ MypyFile:1( class A: @classmethod def f(cls, z: int) -> str: pass -[builtins fixtures/classmethod.py] +[builtins fixtures/classmethod.pyi] [out] MypyFile:1( ClassDef:1( @@ -467,7 +467,7 @@ MypyFile:1( class A: @classmethod def f(cls) -> str: pass -[builtins fixtures/classmethod.py] +[builtins fixtures/classmethod.pyi] [out] MypyFile:1( ClassDef:1( @@ -488,7 +488,7 @@ import typing class A: @property def f(self) -> str: pass -[builtins fixtures/property.py] +[builtins fixtures/property.pyi] [out] MypyFile:1( Import:1(typing) @@ -572,7 +572,7 @@ import m [file m.pyi] from typing import Tuple class A(Tuple[int, str]): pass -[builtins fixtures/tuple.py] +[builtins fixtures/tuple.pyi] [out] MypyFile:1( Import:1(m)) diff --git a/test-data/unit/semanal-errors.test b/test-data/unit/semanal-errors.test index 7fd708ca3057..d563132c1709 100644 --- a/test-data/unit/semanal-errors.test +++ b/test-data/unit/semanal-errors.test @@ -779,7 +779,7 @@ class C(bool): pass # E: 'bool' is not a valid base class class A(int): pass # ok class B(float): pass # ok class D(str): pass # ok -[builtins fixtures/primitives.py] +[builtins fixtures/primitives.pyi] [out] [case testCyclicInheritance] @@ -1013,7 +1013,7 @@ from typing import TypeVar T = TypeVar('T', int, str, bound=bool) # E: TypeVar cannot have both values and an upper bound S = TypeVar('S', covariant=True, contravariant=True) \ # E: TypeVar cannot be both covariant and contravariant -[builtins fixtures/bool.py] +[builtins fixtures/bool.pyi] [case testInvalidTypevarValues] from typing import TypeVar @@ -1136,7 +1136,7 @@ class A: def g(self) -> None: @staticmethod def h(): pass -[builtins fixtures/staticmethod.py] +[builtins fixtures/staticmethod.pyi] [out] main:2: error: 'staticmethod' used with a non-method main: note: In function "g": @@ -1150,7 +1150,7 @@ class A: def g(self) -> None: @classmethod def h(): pass -[builtins fixtures/classmethod.py] +[builtins fixtures/classmethod.pyi] [out] main:2: error: 'classmethod' used with a non-method main: note: In function "g": @@ -1160,7 +1160,7 @@ main:6: error: 'classmethod' used with a non-method import typing @property # E: 'property' used with a non-method def f() -> int: pass -[builtins fixtures/property.py] +[builtins fixtures/property.pyi] [out] [case testInvalidArgCountForProperty] @@ -1170,7 +1170,7 @@ class A: def f(self, x) -> int: pass # E: Too many arguments @property def g() -> int: pass # E: Method must have at least one argument -[builtins fixtures/property.py] +[builtins fixtures/property.pyi] [out] [case testOverloadedProperty] @@ -1182,7 +1182,7 @@ class A: @property # E: Decorated property not supported @overload def f(self) -> int: pass -[builtins fixtures/property.py] +[builtins fixtures/property.pyi] [out] [case testOverloadedProperty2] @@ -1193,7 +1193,7 @@ class A: @property # E: Decorated property not supported @overload def f(self) -> int: pass -[builtins fixtures/property.py] +[builtins fixtures/property.pyi] [out] [case testDecoratedProperty] @@ -1206,7 +1206,7 @@ class A: @property # E: Decorated property not supported @dec def g(self) -> int: pass -[builtins fixtures/property.py] +[builtins fixtures/property.pyi] [out] [case testImportTwoModulesWithSameNameInFunction] @@ -1234,7 +1234,7 @@ y = 1 [case testListTypeAliasWithoutImport] import typing def f() -> List[int]: pass -[builtins fixtures/list.py] +[builtins fixtures/list.pyi] [out] main: note: In function "f": main:2: error: Name 'List' is not defined diff --git a/test-data/unit/semanal-expressions.test b/test-data/unit/semanal-expressions.test index 70d959c6e7f2..7c5728b01f37 100644 --- a/test-data/unit/semanal-expressions.test +++ b/test-data/unit/semanal-expressions.test @@ -382,7 +382,7 @@ MypyFile:1( [case testDictWithKeywordArgs] dict(a=1, b=str()) -[builtins fixtures/dict.py] +[builtins fixtures/dict.pyi] [out] MypyFile:1( ExpressionStmt:1( diff --git a/test-data/unit/semanal-python2.test b/test-data/unit/semanal-python2.test index a4991e201253..97264a5dc503 100644 --- a/test-data/unit/semanal-python2.test +++ b/test-data/unit/semanal-python2.test @@ -38,7 +38,7 @@ MypyFile:1( [case testVariableLengthTuple_python2] from typing import Tuple, cast cast(Tuple[int, ...], ()) -[builtins_py2 fixtures/tuple.py] +[builtins_py2 fixtures/tuple.pyi] [out] MypyFile:1( ImportFrom:1(typing, [Tuple, cast]) diff --git a/test-data/unit/semanal-statements.test b/test-data/unit/semanal-statements.test index bc8614c10214..d5630511ca3f 100644 --- a/test-data/unit/semanal-statements.test +++ b/test-data/unit/semanal-statements.test @@ -771,7 +771,7 @@ except Err as f: f = BaseException() # Fail f = Err() class Err(BaseException): pass -[builtins fixtures/exception.py] +[builtins fixtures/exception.pyi] [out] MypyFile:1( TryStmt:1( diff --git a/test-data/unit/semanal-typealiases.test b/test-data/unit/semanal-typealiases.test index f0e7f391b1e4..5178a71f871f 100644 --- a/test-data/unit/semanal-typealiases.test +++ b/test-data/unit/semanal-typealiases.test @@ -1,7 +1,7 @@ [case testListTypeAlias] from typing import List def f() -> List[int]: pass -[builtins fixtures/list.py] +[builtins fixtures/list.pyi] [out] MypyFile:1( ImportFrom:1(typing, [List]) @@ -14,7 +14,7 @@ MypyFile:1( [case testDictTypeAlias] from typing import Dict def f() -> Dict[int, str]: pass -[builtins fixtures/dict.py] +[builtins fixtures/dict.pyi] [out] MypyFile:1( ImportFrom:1(typing, [Dict]) @@ -27,7 +27,7 @@ MypyFile:1( [case testQualifiedTypeAlias] import typing def f() -> typing.List[int]: pass -[builtins fixtures/list.py] +[builtins fixtures/list.pyi] [out] MypyFile:1( Import:1(typing) @@ -40,7 +40,7 @@ MypyFile:1( [case testTypeApplicationWithTypeAlias] from typing import List List[List[int]] -[builtins fixtures/list.py] +[builtins fixtures/list.pyi] [out] MypyFile:1( ImportFrom:1(typing, [List]) @@ -53,7 +53,7 @@ MypyFile:1( [case testTypeApplicationWithQualifiedTypeAlias] import typing typing.List[typing.List[int]] -[builtins fixtures/list.py] +[builtins fixtures/list.pyi] [out] MypyFile:1( Import:1(typing) @@ -235,7 +235,7 @@ MypyFile:1( from typing import List A = List[int] def f(x: A) -> None: pass -[builtins fixtures/list.py] +[builtins fixtures/list.pyi] [out] MypyFile:1( ImportFrom:1(typing, [List]) diff --git a/test-data/unit/semanal-types.test b/test-data/unit/semanal-types.test index d21a176eacff..35be5643f100 100644 --- a/test-data/unit/semanal-types.test +++ b/test-data/unit/semanal-types.test @@ -680,7 +680,7 @@ from typing import Tuple t = None # type: tuple t1 = None # type: Tuple[object] t2 = None # type: Tuple[int, object] -[builtins fixtures/tuple.py] +[builtins fixtures/tuple.pyi] [out] MypyFile:1( ImportFrom:1(typing, [Tuple]) @@ -700,7 +700,7 @@ MypyFile:1( [case testVariableLengthTuple] from typing import Tuple t = None # type: Tuple[int, ...] -[builtins fixtures/tuple.py] +[builtins fixtures/tuple.pyi] [out] MypyFile:1( ImportFrom:1(typing, [Tuple]) @@ -1251,7 +1251,7 @@ MypyFile:1( [case testTypevarWithValuesAndVariance] from typing import TypeVar T = TypeVar('T', int, str, covariant=True) -[builtins fixtures/bool.py] +[builtins fixtures/bool.pyi] [out] MypyFile:1( ImportFrom:1(typing, [TypeVar]) @@ -1441,7 +1441,7 @@ y = 1 # type: Optional # E: Optional[...] must have exactly one type argument from typing import TypeVar T = TypeVar('T', covariant=True) S = TypeVar('S', contravariant=True) -[builtins fixtures/bool.py] +[builtins fixtures/bool.pyi] [out] MypyFile:1( ImportFrom:1(typing, [TypeVar]) diff --git a/test-data/unit/typexport-basic.test b/test-data/unit/typexport-basic.test index 15c772c23663..2c668f8d557d 100644 --- a/test-data/unit/typexport-basic.test +++ b/test-data/unit/typexport-basic.test @@ -36,7 +36,7 @@ import typing 5 2.3 'foo' -[builtins fixtures/primitives.py] +[builtins fixtures/primitives.pyi] [out] IntExpr(2) : builtins.int FloatExpr(3) : builtins.float @@ -163,7 +163,7 @@ a = 1 a and a a or a not a -[builtins fixtures/bool.py] +[builtins fixtures/bool.pyi] [out] OpExpr(4) : builtins.int OpExpr(5) : builtins.int @@ -176,7 +176,7 @@ a = bool() a and a a or a not a -[builtins fixtures/bool.py] +[builtins fixtures/bool.pyi] [out] OpExpr(4) : builtins.bool OpExpr(5) : builtins.bool @@ -191,7 +191,7 @@ f( class A: pass class B: pass def f(a: A, b: B) -> Tuple[A, B]: pass -[builtins fixtures/tuple-simple.py] +[builtins fixtures/tuple-simple.pyi] [out] CallExpr(3) : Tuple[A, B] CallExpr(4) : A @@ -243,7 +243,7 @@ if a: 1 elif not a: 1 -[builtins fixtures/bool.py] +[builtins fixtures/bool.pyi] [out] NameExpr(3) : builtins.bool IntExpr(4) : builtins.int @@ -256,7 +256,7 @@ IntExpr(6) : builtins.int a = None # type: bool while a: a -[builtins fixtures/bool.py] +[builtins fixtures/bool.pyi] [out] NameExpr(3) : builtins.bool NameExpr(4) : builtins.bool @@ -269,7 +269,7 @@ NameExpr(4) : builtins.bool [case testInferSingleType] import typing x = () -[builtins fixtures/primitives.py] +[builtins fixtures/primitives.pyi] [out] NameExpr(2) : Tuple[] TupleExpr(2) : Tuple[] @@ -279,7 +279,7 @@ TupleExpr(2) : Tuple[] import typing (s, i) = 'x', 1 -[builtins fixtures/primitives.py] +[builtins fixtures/primitives.pyi] [out] NameExpr(3) : builtins.str NameExpr(4) : builtins.int @@ -288,7 +288,7 @@ NameExpr(4) : builtins.int import typing def f() -> None: x = () -[builtins fixtures/primitives.py] +[builtins fixtures/primitives.pyi] [out] NameExpr(3) : Tuple[] TupleExpr(3) : Tuple[] @@ -330,7 +330,7 @@ class A: pass f[A](A()) f[Any](A()) def f(a: T) -> Tuple[T, T]: pass -[builtins fixtures/tuple.py] +[builtins fixtures/tuple.pyi] [out] CallExpr(5) : A CallExpr(5) : Tuple[A, A] @@ -663,14 +663,14 @@ NameExpr(5) : def (a: A[C]) -> B[A[C]] from typing import List a = [] # type: List[A] class A: pass -[builtins fixtures/list.py] +[builtins fixtures/list.pyi] [out] ListExpr(2) : builtins.list[A] [case testInferGenericTypeInTypeAnyContext] from typing import Any a = [] # type: Any -[builtins fixtures/list.py] +[builtins fixtures/list.pyi] [out] ListExpr(2) : builtins.list[Any] @@ -685,7 +685,7 @@ def map(f: Callable[[t], s], a: List[t]) -> List[s]: pass class A: pass class B: pass def f(a: A) -> B: pass -[builtins fixtures/list.py] +[builtins fixtures/list.pyi] [out] CallExpr(4) : builtins.list[B] NameExpr(4) : def (f: def (A) -> B, a: builtins.list[A]) -> builtins.list[B] @@ -722,7 +722,7 @@ NameExpr(3) : def () -> builtins.int ## FuncExpr|NameExpr import typing f = lambda: [1] -[builtins fixtures/list.py] +[builtins fixtures/list.pyi] [out] FuncExpr(3) : def () -> builtins.list[builtins.int] NameExpr(3) : def () -> builtins.list[builtins.int] @@ -733,7 +733,7 @@ f = lambda x: [] # type: Callable[[B], List[A]] class A: pass class B: a = None # type: A -[builtins fixtures/list.py] +[builtins fixtures/list.pyi] [out] FuncExpr(2) : def (B) -> builtins.list[A] ListExpr(2) : builtins.list[A] @@ -749,7 +749,7 @@ def map(f: Callable[[t], s], a: List[t]) -> List[s]: pass class A: pass class B: pass def f(a: A) -> B: pass -[builtins fixtures/list.py] +[builtins fixtures/list.pyi] [out] CallExpr(5) : builtins.list[B] NameExpr(5) : def (f: def (A) -> B, a: builtins.list[A]) -> builtins.list[B] @@ -771,7 +771,7 @@ def map(f: Callable[[t], List[s]], a: List[t]) -> List[s]: pass class A: pass class B: pass def f(a: A) -> B: pass -[builtins fixtures/list.py] +[builtins fixtures/list.pyi] [out] NameExpr(6) : def (f: def (A) -> builtins.list[B], a: builtins.list[A]) -> builtins.list[B] FuncExpr(7) : def (A) -> builtins.list[B] @@ -790,7 +790,7 @@ map( l) def map(f: List[Callable[[t], s]], a: List[t]) -> List[s]: pass class A: pass -[builtins fixtures/list.py] +[builtins fixtures/list.pyi] [out] -- TODO We probably should not silently infer 'Any' types in statically typed -- context. Perhaps just fail instead? @@ -813,7 +813,7 @@ def map(f: Callable[[t], s], a: List[t]) -> List[s]: pass class A: b = None # type: B class B: pass -[builtins fixtures/list.py] +[builtins fixtures/list.pyi] [out] CallExpr(5) : builtins.list[B] NameExpr(5) : def (f: def (A) -> B, a: builtins.list[A]) -> builtins.list[B] @@ -834,7 +834,7 @@ def map(f: Callable[[t], s], a: List[t]) -> List[s]: pass class A: b = None # type: B class B: pass -[builtins fixtures/list.py] +[builtins fixtures/list.pyi] [out] CallExpr(5) : builtins.list[B] NameExpr(5) : def (f: def (A) -> B, a: builtins.list[A]) -> builtins.list[B] @@ -855,7 +855,7 @@ a or [] a = a or [] a = [] or a class A: pass -[builtins fixtures/list.py] +[builtins fixtures/list.pyi] [out] ListExpr(3) : builtins.list[A] NameExpr(3) : builtins.list[A] @@ -1102,7 +1102,7 @@ def m(fun: Callable[[T], V], iter: List[T]) -> None: pass nums = [1] # type: List[int] m(fun, nums) -[builtins fixtures/list.py] +[builtins fixtures/list.pyi] [out] IntExpr(13) : builtins.int ListExpr(13) : builtins.list[builtins.int] @@ -1131,7 +1131,7 @@ NameExpr(6) : def () -> A ## ListExpr|OpExpr|IntExpr from typing import List a = [None] * 3 # type: List[str] -[builtins fixtures/list.py] +[builtins fixtures/list.pyi] [out] IntExpr(3) : builtins.int ListExpr(3) : builtins.list[builtins.str] diff --git a/typeshed b/typeshed index de4e87f574e4..cc1f92103d96 160000 --- a/typeshed +++ b/typeshed @@ -1 +1 @@ -Subproject commit de4e87f574e40bcfea15e0254d1640f63a737c6e +Subproject commit cc1f92103d965eab6dc3878afb683ed71bbb56d3