after_merge
stringlengths
28
79.6k
before_merge
stringlengths
20
79.6k
url
stringlengths
38
71
full_traceback
stringlengths
43
922k
traceback_type
stringclasses
555 values
def visit_dictionary_comprehension(self, e: DictionaryComprehension) -> Type: """Type check a dictionary comprehension.""" with self.chk.binder.frame_context(can_skip=True, fall_through=0): 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="<dictionary-comprehension>", variables=[ktdef, vtdef], ) return self.check_call( constructor, [e.key, e.value], [nodes.ARG_POS, nodes.ARG_POS], e )[0]
def visit_dictionary_comprehension(self, e: DictionaryComprehension) -> Type: """Type check a dictionary comprehension.""" 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="<dictionary-comprehension>", variables=[ktdef, vtdef], ) return self.check_call( constructor, [e.key, e.value], [nodes.ARG_POS, nodes.ARG_POS], e )[0]
https://github.com/python/mypy/issues/1289
Traceback (most recent call last): File "./scripts/mypy", line 6, in <module> main(__file__) File "mypy/mypy/main.py", line 50, in main type_check_only(sources, bin_dir, options) File "mypy/mypy/main.py", line 94, in type_check_only python_path=options.python_path) File "mypy/mypy/build.py", line 210, in build result = manager.process(initial_states) File "mypy/mypy/build.py", line 425, in process next.process() File "mypy/mypy/build.py", line 930, in process self.type_checker().visit_file(self.tree, self.tree.path) File "mypy/mypy/checker.py", line 409, in visit_file self.accept(d) File "mypy/mypy/checker.py", line 450, in accept typ = node.accept(self) File "mypy/mypy/nodes.py", line 707, in accept return visitor.visit_try_stmt(self) File "mypy/mypy/checker.py", line 1732, in visit_try_stmt self.accept(s.else_body) File "mypy/mypy/checker.py", line 450, in accept typ = node.accept(self) File "mypy/mypy/nodes.py", line 526, in accept return visitor.visit_block(self) File "mypy/mypy/checker.py", line 1113, in visit_block self.accept(s) File "mypy/mypy/checker.py", line 450, in accept typ = node.accept(self) File "mypy/mypy/nodes.py", line 382, in accept return visitor.visit_func_def(self) File "mypy/mypy/checker.py", line 594, in visit_func_def 'redefinition with type') File "mypy/mypy/checker.py", line 2117, in check_subtype if not is_subtype(subtype, supertype): File "mypy/mypy/subtypes.py", line 49, in is_subtype return left.accept(SubtypeVisitor(right, type_parameter_checker)) AttributeError: 'NoneType' object has no attribute 'accept'
AttributeError
def visit_conditional_expr(self, e: ConditionalExpr) -> Type: cond_type = self.accept(e.cond) self.check_usable_type(cond_type, e) ctx = self.chk.type_context[-1] # Gain type information from isinstance if it is there # but only for the current expression if_map, else_map = self.chk.find_isinstance_check(e.cond) if_type = self.analyze_cond_branch(if_map, e.if_expr, context=ctx) if not mypy.checker.is_valid_inferred_type(if_type): # Analyze the right branch disregarding the left branch. else_type = self.analyze_cond_branch(else_map, e.else_expr, context=ctx) # If it would make a difference, re-analyze the left # branch using the right branch's type as context. if ctx is None or not is_equivalent(else_type, ctx): # TODO: If it's possible that the previous analysis of # the left branch produced errors that are avoided # using this context, suppress those errors. if_type = self.analyze_cond_branch(if_map, e.if_expr, context=else_type) else: # Analyze the right branch in the context of the left # branch's type. else_type = self.analyze_cond_branch(else_map, e.else_expr, context=if_type) res = join.join_types(if_type, else_type) return res
def visit_conditional_expr(self, e: ConditionalExpr) -> Type: cond_type = self.accept(e.cond) self.check_usable_type(cond_type, e) ctx = self.chk.type_context[-1] # Gain type information from isinstance if it is there # but only for the current expression if_map, else_map = mypy.checker.find_isinstance_check(e.cond, self.chk.type_map) if_type = self.analyze_cond_branch(if_map, e.if_expr, context=ctx) if not mypy.checker.is_valid_inferred_type(if_type): # Analyze the right branch disregarding the left branch. else_type = self.analyze_cond_branch(else_map, e.else_expr, context=ctx) # If it would make a difference, re-analyze the left # branch using the right branch's type as context. if ctx is None or not is_equivalent(else_type, ctx): # TODO: If it's possible that the previous analysis of # the left branch produced errors that are avoided # using this context, suppress those errors. if_type = self.analyze_cond_branch(if_map, e.if_expr, context=else_type) else: # Analyze the right branch in the context of the left # branch's type. else_type = self.analyze_cond_branch(else_map, e.else_expr, context=if_type) res = join.join_types(if_type, else_type) return res
https://github.com/python/mypy/issues/1289
Traceback (most recent call last): File "./scripts/mypy", line 6, in <module> main(__file__) File "mypy/mypy/main.py", line 50, in main type_check_only(sources, bin_dir, options) File "mypy/mypy/main.py", line 94, in type_check_only python_path=options.python_path) File "mypy/mypy/build.py", line 210, in build result = manager.process(initial_states) File "mypy/mypy/build.py", line 425, in process next.process() File "mypy/mypy/build.py", line 930, in process self.type_checker().visit_file(self.tree, self.tree.path) File "mypy/mypy/checker.py", line 409, in visit_file self.accept(d) File "mypy/mypy/checker.py", line 450, in accept typ = node.accept(self) File "mypy/mypy/nodes.py", line 707, in accept return visitor.visit_try_stmt(self) File "mypy/mypy/checker.py", line 1732, in visit_try_stmt self.accept(s.else_body) File "mypy/mypy/checker.py", line 450, in accept typ = node.accept(self) File "mypy/mypy/nodes.py", line 526, in accept return visitor.visit_block(self) File "mypy/mypy/checker.py", line 1113, in visit_block self.accept(s) File "mypy/mypy/checker.py", line 450, in accept typ = node.accept(self) File "mypy/mypy/nodes.py", line 382, in accept return visitor.visit_func_def(self) File "mypy/mypy/checker.py", line 594, in visit_func_def 'redefinition with type') File "mypy/mypy/checker.py", line 2117, in check_subtype if not is_subtype(subtype, supertype): File "mypy/mypy/subtypes.py", line 49, in is_subtype return left.accept(SubtypeVisitor(right, type_parameter_checker)) AttributeError: 'NoneType' object has no attribute 'accept'
AttributeError
def analyze_cond_branch( self, map: Optional[Dict[Expression, Type]], node: Expression, context: Optional[Type], ) -> Type: with self.chk.binder.frame_context(can_skip=True, fall_through=0): if map is None: # We still need to type check node, in case we want to # process it for isinstance checks later self.accept(node, context=context) return UninhabitedType() self.chk.push_type_map(map) return self.accept(node, context=context)
def analyze_cond_branch( self, map: Optional[Dict[Expression, Type]], node: Expression, context: Optional[Type], ) -> Type: with self.chk.binder.frame_context(): if map: for var, type in map.items(): self.chk.binder.push(var, type) return self.accept(node, context=context)
https://github.com/python/mypy/issues/1289
Traceback (most recent call last): File "./scripts/mypy", line 6, in <module> main(__file__) File "mypy/mypy/main.py", line 50, in main type_check_only(sources, bin_dir, options) File "mypy/mypy/main.py", line 94, in type_check_only python_path=options.python_path) File "mypy/mypy/build.py", line 210, in build result = manager.process(initial_states) File "mypy/mypy/build.py", line 425, in process next.process() File "mypy/mypy/build.py", line 930, in process self.type_checker().visit_file(self.tree, self.tree.path) File "mypy/mypy/checker.py", line 409, in visit_file self.accept(d) File "mypy/mypy/checker.py", line 450, in accept typ = node.accept(self) File "mypy/mypy/nodes.py", line 707, in accept return visitor.visit_try_stmt(self) File "mypy/mypy/checker.py", line 1732, in visit_try_stmt self.accept(s.else_body) File "mypy/mypy/checker.py", line 450, in accept typ = node.accept(self) File "mypy/mypy/nodes.py", line 526, in accept return visitor.visit_block(self) File "mypy/mypy/checker.py", line 1113, in visit_block self.accept(s) File "mypy/mypy/checker.py", line 450, in accept typ = node.accept(self) File "mypy/mypy/nodes.py", line 382, in accept return visitor.visit_func_def(self) File "mypy/mypy/checker.py", line 594, in visit_func_def 'redefinition with type') File "mypy/mypy/checker.py", line 2117, in check_subtype if not is_subtype(subtype, supertype): File "mypy/mypy/subtypes.py", line 49, in is_subtype return left.accept(SubtypeVisitor(right, type_parameter_checker)) AttributeError: 'NoneType' object has no attribute 'accept'
AttributeError
def process_options( args: List[str], require_targets: bool = True ) -> Tuple[List[BuildSource], Options]: """Parse command line arguments.""" # Make the help output a little less jarring. help_factory = lambda prog: argparse.RawDescriptionHelpFormatter( prog=prog, max_help_position=28 ) parser = argparse.ArgumentParser( prog="mypy", epilog=FOOTER, fromfile_prefix_chars="@", formatter_class=help_factory, ) # Unless otherwise specified, arguments will be parsed directly onto an # Options object. Options that require further processing should have # their `dest` prefixed with `special-opts:`, which will cause them to be # parsed into the separate special_opts namespace object. parser.add_argument( "-v", "--verbose", action="count", dest="verbosity", help="more verbose messages", ) parser.add_argument( "-V", "--version", action="version", version="%(prog)s " + __version__ ) parser.add_argument( "--python-version", type=parse_version, metavar="x.y", help="use Python x.y" ) parser.add_argument( "--platform", action="store", metavar="PLATFORM", help="typecheck special-cased code for the given OS platform " "(defaults to sys.platform).", ) 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", ) parser.add_argument( "--almost-silent", action="store_true", help="like --silent-imports but reports the imports as errors", ) parser.add_argument( "--disallow-untyped-calls", action="store_true", help="disallow calling functions without type annotations" " from functions with type annotations", ) parser.add_argument( "--disallow-untyped-defs", action="store_true", help="disallow defining functions without type annotations" " or with incomplete type annotations", ) parser.add_argument( "--check-untyped-defs", action="store_true", help="type check the interior of functions without type annotations", ) parser.add_argument( "--disallow-subclassing-any", action="store_true", help="disallow subclassing values of type 'Any' when defining classes", ) parser.add_argument( "--warn-incomplete-stub", action="store_true", help="warn if missing type annotation in typeshed, only relevant with" " --check-untyped-defs enabled", ) parser.add_argument( "--warn-redundant-casts", action="store_true", help="warn about casting an expression to its inferred type", ) parser.add_argument( "--warn-no-return", action="store_true", help="warn about functions that end without returning", ) parser.add_argument( "--warn-unused-ignores", action="store_true", help="warn about unneeded '# type: ignore' comments", ) parser.add_argument( "--hide-error-context", action="store_true", dest="hide_error_context", help="Hide context notes before errors", ) parser.add_argument( "--fast-parser", action="store_true", help="enable experimental fast parser" ) parser.add_argument( "-i", "--incremental", action="store_true", help="enable experimental module cache", ) parser.add_argument( "--cache-dir", action="store", metavar="DIR", help="store module cache info in the given folder in incremental mode " "(defaults to '{}')".format(defaults.CACHE_DIR), ) parser.add_argument( "--strict-optional", action="store_true", dest="strict_optional", help="enable experimental strict Optional checks", ) parser.add_argument( "--strict-optional-whitelist", metavar="GLOB", nargs="*", help="suppress strict Optional errors in all but the provided files " "(experimental -- read documentation before using!). " "Implies --strict-optional. Has the undesirable side-effect of " "suppressing other errors in non-whitelisted files.", ) 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", ) parser.add_argument( "--custom-typing", metavar="MODULE", dest="custom_typing_module", help="use a custom typing module", ) parser.add_argument( "--scripts-are-modules", action="store_true", help="Script x becomes module x instead of __main__", ) parser.add_argument( "--config-file", help="Configuration file, must have a [mypy] section (defaults to {})".format( defaults.CONFIG_FILE ), ) parser.add_argument( "--show-column-numbers", action="store_true", dest="show_column_numbers", help="Show column numbers in error messages", ) # hidden options # --shadow-file a.py tmp.py will typecheck tmp.py in place of a.py. # Useful for tools to make transformations to a file to get more # information from a mypy run without having to change the file in-place # (e.g. by adding a call to reveal_type). parser.add_argument( "--shadow-file", metavar="PATH", nargs=2, dest="shadow_file", help=argparse.SUPPRESS, ) # --debug-cache will disable any cache-related compressions/optimizations, # which will make the cache writing process output pretty-printed JSON (which # is easier to debug). parser.add_argument("--debug-cache", action="store_true", help=argparse.SUPPRESS) # deprecated options parser.add_argument( "--silent", action="store_true", dest="special-opts:silent", help=argparse.SUPPRESS, ) parser.add_argument( "-f", "--dirty-stubs", action="store_true", dest="special-opts:dirty_stubs", help=argparse.SUPPRESS, ) parser.add_argument( "--use-python-path", action="store_true", dest="special-opts:use_python_path", help=argparse.SUPPRESS, ) report_group = parser.add_argument_group( title="report generation", description="Generate a report in the specified format.", ) for report_type in sorted(reporter_classes): report_group.add_argument( "--%s-report" % report_type.replace("_", "-"), metavar="DIR", dest="special-opts:%s_report" % report_type, ) code_group = parser.add_argument_group( title="How to specify the code to type check" ) code_group.add_argument( "-m", "--module", action="append", metavar="MODULE", dest="special-opts:modules", help="type-check module; can repeat for more modules", ) # TODO: `mypy -p A -p B` currently silently ignores ignores A # (last option wins). Perhaps -c, -m and -p could just be # command-line flags that modify how we interpret self.files? code_group.add_argument( "-c", "--command", action="append", metavar="PROGRAM_TEXT", dest="special-opts:command", help="type-check program passed in as string", ) code_group.add_argument( "-p", "--package", metavar="PACKAGE", dest="special-opts:package", help="type-check all files in a directory", ) code_group.add_argument( metavar="files", nargs="*", dest="special-opts:files", help="type-check given files or directories", ) # Parse arguments once into a dummy namespace so we can get the # filename for the config file. dummy = argparse.Namespace() parser.parse_args(args, dummy) config_file = dummy.config_file or defaults.CONFIG_FILE # Parse config file first, so command line can override. options = Options() if config_file and os.path.exists(config_file): parse_config_file(options, config_file) # Parse command line for real, using a split namespace. special_opts = argparse.Namespace() parser.parse_args(args, SplitNamespace(options, special_opts, "special-opts:")) # --use-python-path is no longer supported; explain why. if special_opts.use_python_path: parser.error( "Sorry, --use-python-path is no longer supported.\n" "If you are trying this because your code depends on a library module,\n" "you should really investigate how to obtain stubs for that module.\n" "See https://github.com/python/mypy/issues/1411 for more discussion." ) # warn about deprecated options if special_opts.silent: print("Warning: --silent is deprecated; use --silent-imports", file=sys.stderr) options.silent_imports = True if special_opts.dirty_stubs: print( "Warning: -f/--dirty-stubs is deprecated and no longer necessary. Mypy no longer " "checks the git status of stubs.", file=sys.stderr, ) # Check for invalid argument combinations. if require_targets: code_methods = sum( bool(c) for c in [ special_opts.modules, special_opts.command, special_opts.package, special_opts.files, ] ) if code_methods == 0: parser.error("Missing target module, package, files, or command.") elif code_methods > 1: parser.error("May only specify one of: module, package, files, or command.") # Set build flags. if options.strict_optional_whitelist is not None: # TODO: Deprecate, then kill this flag options.strict_optional = True if options.strict_optional: experiments.STRICT_OPTIONAL = True # Set reports. for flag, val in vars(special_opts).items(): if flag.endswith("_report") and val is not None: report_type = flag[:-7].replace("_", "-") report_dir = val options.report_dirs[report_type] = report_dir # Set target. if special_opts.modules: options.build_type = BuildType.MODULE targets = [BuildSource(None, m, None) for m in special_opts.modules] return targets, options elif special_opts.package: if ( os.sep in special_opts.package or os.altsep and os.altsep in special_opts.package ): fail( "Package name '{}' cannot have a slash in it.".format( special_opts.package ) ) options.build_type = BuildType.MODULE lib_path = [os.getcwd()] + build.mypy_path() targets = build.find_modules_recursive(special_opts.package, lib_path) if not targets: fail("Can't find package '{}'".format(special_opts.package)) return targets, options elif special_opts.command: options.build_type = BuildType.PROGRAM_TEXT return [BuildSource(None, None, "\n".join(special_opts.command))], options else: targets = [] for f in special_opts.files: if f.endswith(PY_EXTENSIONS): targets.append(BuildSource(f, crawl_up(f)[1], None)) elif os.path.isdir(f): sub_targets = expand_dir(f) if not sub_targets: fail("There are no .py[i] files in directory '{}'".format(f)) targets.extend(sub_targets) else: mod = os.path.basename(f) if options.scripts_are_modules else None targets.append(BuildSource(f, mod, None)) return targets, options
def process_options( args: List[str], require_targets: bool = True ) -> Tuple[List[BuildSource], Options]: """Parse command line arguments.""" # Make the help output a little less jarring. help_factory = lambda prog: argparse.RawDescriptionHelpFormatter( prog=prog, max_help_position=28 ) parser = argparse.ArgumentParser( prog="mypy", epilog=FOOTER, fromfile_prefix_chars="@", formatter_class=help_factory, ) # Unless otherwise specified, arguments will be parsed directly onto an # Options object. Options that require further processing should have # their `dest` prefixed with `special-opts:`, which will cause them to be # parsed into the separate special_opts namespace object. parser.add_argument( "-v", "--verbose", action="count", dest="verbosity", help="more verbose messages", ) parser.add_argument( "-V", "--version", action="version", version="%(prog)s " + __version__ ) parser.add_argument( "--python-version", type=parse_version, metavar="x.y", help="use Python x.y" ) parser.add_argument( "--platform", action="store", metavar="PLATFORM", help="typecheck special-cased code for the given OS platform " "(defaults to sys.platform).", ) 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", ) parser.add_argument( "--almost-silent", action="store_true", help="like --silent-imports but reports the imports as errors", ) parser.add_argument( "--disallow-untyped-calls", action="store_true", help="disallow calling functions without type annotations" " from functions with type annotations", ) parser.add_argument( "--disallow-untyped-defs", action="store_true", help="disallow defining functions without type annotations" " or with incomplete type annotations", ) parser.add_argument( "--check-untyped-defs", action="store_true", help="type check the interior of functions without type annotations", ) parser.add_argument( "--disallow-subclassing-any", action="store_true", help="disallow subclassing values of type 'Any' when defining classes", ) parser.add_argument( "--warn-incomplete-stub", action="store_true", help="warn if missing type annotation in typeshed, only relevant with" " --check-untyped-defs enabled", ) parser.add_argument( "--warn-redundant-casts", action="store_true", help="warn about casting an expression to its inferred type", ) parser.add_argument( "--warn-unused-ignores", action="store_true", help="warn about unneeded '# type: ignore' comments", ) parser.add_argument( "--hide-error-context", action="store_true", dest="hide_error_context", help="Hide context notes before errors", ) parser.add_argument( "--fast-parser", action="store_true", help="enable experimental fast parser" ) parser.add_argument( "-i", "--incremental", action="store_true", help="enable experimental module cache", ) parser.add_argument( "--cache-dir", action="store", metavar="DIR", help="store module cache info in the given folder in incremental mode " "(defaults to '{}')".format(defaults.CACHE_DIR), ) parser.add_argument( "--strict-optional", action="store_true", dest="strict_optional", help="enable experimental strict Optional checks", ) parser.add_argument( "--strict-optional-whitelist", metavar="GLOB", nargs="*", help="suppress strict Optional errors in all but the provided files " "(experimental -- read documentation before using!). " "Implies --strict-optional. Has the undesirable side-effect of " "suppressing other errors in non-whitelisted files.", ) 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", ) parser.add_argument( "--custom-typing", metavar="MODULE", dest="custom_typing_module", help="use a custom typing module", ) parser.add_argument( "--scripts-are-modules", action="store_true", help="Script x becomes module x instead of __main__", ) parser.add_argument( "--config-file", help="Configuration file, must have a [mypy] section (defaults to {})".format( defaults.CONFIG_FILE ), ) parser.add_argument( "--show-column-numbers", action="store_true", dest="show_column_numbers", help="Show column numbers in error messages", ) # hidden options # --shadow-file a.py tmp.py will typecheck tmp.py in place of a.py. # Useful for tools to make transformations to a file to get more # information from a mypy run without having to change the file in-place # (e.g. by adding a call to reveal_type). parser.add_argument( "--shadow-file", metavar="PATH", nargs=2, dest="shadow_file", help=argparse.SUPPRESS, ) # --debug-cache will disable any cache-related compressions/optimizations, # which will make the cache writing process output pretty-printed JSON (which # is easier to debug). parser.add_argument("--debug-cache", action="store_true", help=argparse.SUPPRESS) # deprecated options parser.add_argument( "--silent", action="store_true", dest="special-opts:silent", help=argparse.SUPPRESS, ) parser.add_argument( "-f", "--dirty-stubs", action="store_true", dest="special-opts:dirty_stubs", help=argparse.SUPPRESS, ) parser.add_argument( "--use-python-path", action="store_true", dest="special-opts:use_python_path", help=argparse.SUPPRESS, ) report_group = parser.add_argument_group( title="report generation", description="Generate a report in the specified format.", ) for report_type in sorted(reporter_classes): report_group.add_argument( "--%s-report" % report_type.replace("_", "-"), metavar="DIR", dest="special-opts:%s_report" % report_type, ) code_group = parser.add_argument_group( title="How to specify the code to type check" ) code_group.add_argument( "-m", "--module", action="append", metavar="MODULE", dest="special-opts:modules", help="type-check module; can repeat for more modules", ) # TODO: `mypy -p A -p B` currently silently ignores ignores A # (last option wins). Perhaps -c, -m and -p could just be # command-line flags that modify how we interpret self.files? code_group.add_argument( "-c", "--command", action="append", metavar="PROGRAM_TEXT", dest="special-opts:command", help="type-check program passed in as string", ) code_group.add_argument( "-p", "--package", metavar="PACKAGE", dest="special-opts:package", help="type-check all files in a directory", ) code_group.add_argument( metavar="files", nargs="*", dest="special-opts:files", help="type-check given files or directories", ) # Parse arguments once into a dummy namespace so we can get the # filename for the config file. dummy = argparse.Namespace() parser.parse_args(args, dummy) config_file = dummy.config_file or defaults.CONFIG_FILE # Parse config file first, so command line can override. options = Options() if config_file and os.path.exists(config_file): parse_config_file(options, config_file) # Parse command line for real, using a split namespace. special_opts = argparse.Namespace() parser.parse_args(args, SplitNamespace(options, special_opts, "special-opts:")) # --use-python-path is no longer supported; explain why. if special_opts.use_python_path: parser.error( "Sorry, --use-python-path is no longer supported.\n" "If you are trying this because your code depends on a library module,\n" "you should really investigate how to obtain stubs for that module.\n" "See https://github.com/python/mypy/issues/1411 for more discussion." ) # warn about deprecated options if special_opts.silent: print("Warning: --silent is deprecated; use --silent-imports", file=sys.stderr) options.silent_imports = True if special_opts.dirty_stubs: print( "Warning: -f/--dirty-stubs is deprecated and no longer necessary. Mypy no longer " "checks the git status of stubs.", file=sys.stderr, ) # Check for invalid argument combinations. if require_targets: code_methods = sum( bool(c) for c in [ special_opts.modules, special_opts.command, special_opts.package, special_opts.files, ] ) if code_methods == 0: parser.error("Missing target module, package, files, or command.") elif code_methods > 1: parser.error("May only specify one of: module, package, files, or command.") # Set build flags. if options.strict_optional_whitelist is not None: # TODO: Deprecate, then kill this flag options.strict_optional = True if options.strict_optional: experiments.STRICT_OPTIONAL = True # Set reports. for flag, val in vars(special_opts).items(): if flag.endswith("_report") and val is not None: report_type = flag[:-7].replace("_", "-") report_dir = val options.report_dirs[report_type] = report_dir # Set target. if special_opts.modules: options.build_type = BuildType.MODULE targets = [BuildSource(None, m, None) for m in special_opts.modules] return targets, options elif special_opts.package: if ( os.sep in special_opts.package or os.altsep and os.altsep in special_opts.package ): fail( "Package name '{}' cannot have a slash in it.".format( special_opts.package ) ) options.build_type = BuildType.MODULE lib_path = [os.getcwd()] + build.mypy_path() targets = build.find_modules_recursive(special_opts.package, lib_path) if not targets: fail("Can't find package '{}'".format(special_opts.package)) return targets, options elif special_opts.command: options.build_type = BuildType.PROGRAM_TEXT return [BuildSource(None, None, "\n".join(special_opts.command))], options else: targets = [] for f in special_opts.files: if f.endswith(PY_EXTENSIONS): targets.append(BuildSource(f, crawl_up(f)[1], None)) elif os.path.isdir(f): sub_targets = expand_dir(f) if not sub_targets: fail("There are no .py[i] files in directory '{}'".format(f)) targets.extend(sub_targets) else: mod = os.path.basename(f) if options.scripts_are_modules else None targets.append(BuildSource(f, mod, None)) return targets, options
https://github.com/python/mypy/issues/1289
Traceback (most recent call last): File "./scripts/mypy", line 6, in <module> main(__file__) File "mypy/mypy/main.py", line 50, in main type_check_only(sources, bin_dir, options) File "mypy/mypy/main.py", line 94, in type_check_only python_path=options.python_path) File "mypy/mypy/build.py", line 210, in build result = manager.process(initial_states) File "mypy/mypy/build.py", line 425, in process next.process() File "mypy/mypy/build.py", line 930, in process self.type_checker().visit_file(self.tree, self.tree.path) File "mypy/mypy/checker.py", line 409, in visit_file self.accept(d) File "mypy/mypy/checker.py", line 450, in accept typ = node.accept(self) File "mypy/mypy/nodes.py", line 707, in accept return visitor.visit_try_stmt(self) File "mypy/mypy/checker.py", line 1732, in visit_try_stmt self.accept(s.else_body) File "mypy/mypy/checker.py", line 450, in accept typ = node.accept(self) File "mypy/mypy/nodes.py", line 526, in accept return visitor.visit_block(self) File "mypy/mypy/checker.py", line 1113, in visit_block self.accept(s) File "mypy/mypy/checker.py", line 450, in accept typ = node.accept(self) File "mypy/mypy/nodes.py", line 382, in accept return visitor.visit_func_def(self) File "mypy/mypy/checker.py", line 594, in visit_func_def 'redefinition with type') File "mypy/mypy/checker.py", line 2117, in check_subtype if not is_subtype(subtype, supertype): File "mypy/mypy/subtypes.py", line 49, in is_subtype return left.accept(SubtypeVisitor(right, type_parameter_checker)) AttributeError: 'NoneType' object has no attribute 'accept'
AttributeError
def __init__(self, value: int) -> None: self.value = value self.literal_hash = ("Literal", value)
def __init__(self, value: int) -> None: self.value = value self.literal_hash = value
https://github.com/python/mypy/issues/1289
Traceback (most recent call last): File "./scripts/mypy", line 6, in <module> main(__file__) File "mypy/mypy/main.py", line 50, in main type_check_only(sources, bin_dir, options) File "mypy/mypy/main.py", line 94, in type_check_only python_path=options.python_path) File "mypy/mypy/build.py", line 210, in build result = manager.process(initial_states) File "mypy/mypy/build.py", line 425, in process next.process() File "mypy/mypy/build.py", line 930, in process self.type_checker().visit_file(self.tree, self.tree.path) File "mypy/mypy/checker.py", line 409, in visit_file self.accept(d) File "mypy/mypy/checker.py", line 450, in accept typ = node.accept(self) File "mypy/mypy/nodes.py", line 707, in accept return visitor.visit_try_stmt(self) File "mypy/mypy/checker.py", line 1732, in visit_try_stmt self.accept(s.else_body) File "mypy/mypy/checker.py", line 450, in accept typ = node.accept(self) File "mypy/mypy/nodes.py", line 526, in accept return visitor.visit_block(self) File "mypy/mypy/checker.py", line 1113, in visit_block self.accept(s) File "mypy/mypy/checker.py", line 450, in accept typ = node.accept(self) File "mypy/mypy/nodes.py", line 382, in accept return visitor.visit_func_def(self) File "mypy/mypy/checker.py", line 594, in visit_func_def 'redefinition with type') File "mypy/mypy/checker.py", line 2117, in check_subtype if not is_subtype(subtype, supertype): File "mypy/mypy/subtypes.py", line 49, in is_subtype return left.accept(SubtypeVisitor(right, type_parameter_checker)) AttributeError: 'NoneType' object has no attribute 'accept'
AttributeError
def __init__(self, value: str) -> None: self.value = value self.literal_hash = ("Literal", value)
def __init__(self, value: str) -> None: self.value = value self.literal_hash = value
https://github.com/python/mypy/issues/1289
Traceback (most recent call last): File "./scripts/mypy", line 6, in <module> main(__file__) File "mypy/mypy/main.py", line 50, in main type_check_only(sources, bin_dir, options) File "mypy/mypy/main.py", line 94, in type_check_only python_path=options.python_path) File "mypy/mypy/build.py", line 210, in build result = manager.process(initial_states) File "mypy/mypy/build.py", line 425, in process next.process() File "mypy/mypy/build.py", line 930, in process self.type_checker().visit_file(self.tree, self.tree.path) File "mypy/mypy/checker.py", line 409, in visit_file self.accept(d) File "mypy/mypy/checker.py", line 450, in accept typ = node.accept(self) File "mypy/mypy/nodes.py", line 707, in accept return visitor.visit_try_stmt(self) File "mypy/mypy/checker.py", line 1732, in visit_try_stmt self.accept(s.else_body) File "mypy/mypy/checker.py", line 450, in accept typ = node.accept(self) File "mypy/mypy/nodes.py", line 526, in accept return visitor.visit_block(self) File "mypy/mypy/checker.py", line 1113, in visit_block self.accept(s) File "mypy/mypy/checker.py", line 450, in accept typ = node.accept(self) File "mypy/mypy/nodes.py", line 382, in accept return visitor.visit_func_def(self) File "mypy/mypy/checker.py", line 594, in visit_func_def 'redefinition with type') File "mypy/mypy/checker.py", line 2117, in check_subtype if not is_subtype(subtype, supertype): File "mypy/mypy/subtypes.py", line 49, in is_subtype return left.accept(SubtypeVisitor(right, type_parameter_checker)) AttributeError: 'NoneType' object has no attribute 'accept'
AttributeError
def __init__(self, value: float) -> None: self.value = value self.literal_hash = ("Literal", value)
def __init__(self, value: float) -> None: self.value = value self.literal_hash = value
https://github.com/python/mypy/issues/1289
Traceback (most recent call last): File "./scripts/mypy", line 6, in <module> main(__file__) File "mypy/mypy/main.py", line 50, in main type_check_only(sources, bin_dir, options) File "mypy/mypy/main.py", line 94, in type_check_only python_path=options.python_path) File "mypy/mypy/build.py", line 210, in build result = manager.process(initial_states) File "mypy/mypy/build.py", line 425, in process next.process() File "mypy/mypy/build.py", line 930, in process self.type_checker().visit_file(self.tree, self.tree.path) File "mypy/mypy/checker.py", line 409, in visit_file self.accept(d) File "mypy/mypy/checker.py", line 450, in accept typ = node.accept(self) File "mypy/mypy/nodes.py", line 707, in accept return visitor.visit_try_stmt(self) File "mypy/mypy/checker.py", line 1732, in visit_try_stmt self.accept(s.else_body) File "mypy/mypy/checker.py", line 450, in accept typ = node.accept(self) File "mypy/mypy/nodes.py", line 526, in accept return visitor.visit_block(self) File "mypy/mypy/checker.py", line 1113, in visit_block self.accept(s) File "mypy/mypy/checker.py", line 450, in accept typ = node.accept(self) File "mypy/mypy/nodes.py", line 382, in accept return visitor.visit_func_def(self) File "mypy/mypy/checker.py", line 594, in visit_func_def 'redefinition with type') File "mypy/mypy/checker.py", line 2117, in check_subtype if not is_subtype(subtype, supertype): File "mypy/mypy/subtypes.py", line 49, in is_subtype return left.accept(SubtypeVisitor(right, type_parameter_checker)) AttributeError: 'NoneType' object has no attribute 'accept'
AttributeError
def __init__(self, value: complex) -> None: self.value = value self.literal_hash = ("Literal", value)
def __init__(self, value: complex) -> None: self.value = value self.literal_hash = value
https://github.com/python/mypy/issues/1289
Traceback (most recent call last): File "./scripts/mypy", line 6, in <module> main(__file__) File "mypy/mypy/main.py", line 50, in main type_check_only(sources, bin_dir, options) File "mypy/mypy/main.py", line 94, in type_check_only python_path=options.python_path) File "mypy/mypy/build.py", line 210, in build result = manager.process(initial_states) File "mypy/mypy/build.py", line 425, in process next.process() File "mypy/mypy/build.py", line 930, in process self.type_checker().visit_file(self.tree, self.tree.path) File "mypy/mypy/checker.py", line 409, in visit_file self.accept(d) File "mypy/mypy/checker.py", line 450, in accept typ = node.accept(self) File "mypy/mypy/nodes.py", line 707, in accept return visitor.visit_try_stmt(self) File "mypy/mypy/checker.py", line 1732, in visit_try_stmt self.accept(s.else_body) File "mypy/mypy/checker.py", line 450, in accept typ = node.accept(self) File "mypy/mypy/nodes.py", line 526, in accept return visitor.visit_block(self) File "mypy/mypy/checker.py", line 1113, in visit_block self.accept(s) File "mypy/mypy/checker.py", line 450, in accept typ = node.accept(self) File "mypy/mypy/nodes.py", line 382, in accept return visitor.visit_func_def(self) File "mypy/mypy/checker.py", line 594, in visit_func_def 'redefinition with type') File "mypy/mypy/checker.py", line 2117, in check_subtype if not is_subtype(subtype, supertype): File "mypy/mypy/subtypes.py", line 49, in is_subtype return left.accept(SubtypeVisitor(right, type_parameter_checker)) AttributeError: 'NoneType' object has no attribute 'accept'
AttributeError
def __init__(self, base: Expression, index: Expression) -> None: self.base = base self.index = index self.analyzed = None if self.index.literal == LITERAL_YES: self.literal = self.base.literal self.literal_hash = ("Index", base.literal_hash, index.literal_hash)
def __init__(self, base: Expression, index: Expression) -> None: self.base = base self.index = index self.analyzed = None if self.index.literal == LITERAL_YES: self.literal = self.base.literal self.literal_hash = ("Member", base.literal_hash, index.literal_hash)
https://github.com/python/mypy/issues/1289
Traceback (most recent call last): File "./scripts/mypy", line 6, in <module> main(__file__) File "mypy/mypy/main.py", line 50, in main type_check_only(sources, bin_dir, options) File "mypy/mypy/main.py", line 94, in type_check_only python_path=options.python_path) File "mypy/mypy/build.py", line 210, in build result = manager.process(initial_states) File "mypy/mypy/build.py", line 425, in process next.process() File "mypy/mypy/build.py", line 930, in process self.type_checker().visit_file(self.tree, self.tree.path) File "mypy/mypy/checker.py", line 409, in visit_file self.accept(d) File "mypy/mypy/checker.py", line 450, in accept typ = node.accept(self) File "mypy/mypy/nodes.py", line 707, in accept return visitor.visit_try_stmt(self) File "mypy/mypy/checker.py", line 1732, in visit_try_stmt self.accept(s.else_body) File "mypy/mypy/checker.py", line 450, in accept typ = node.accept(self) File "mypy/mypy/nodes.py", line 526, in accept return visitor.visit_block(self) File "mypy/mypy/checker.py", line 1113, in visit_block self.accept(s) File "mypy/mypy/checker.py", line 450, in accept typ = node.accept(self) File "mypy/mypy/nodes.py", line 382, in accept return visitor.visit_func_def(self) File "mypy/mypy/checker.py", line 594, in visit_func_def 'redefinition with type') File "mypy/mypy/checker.py", line 2117, in check_subtype if not is_subtype(subtype, supertype): File "mypy/mypy/subtypes.py", line 49, in is_subtype return left.accept(SubtypeVisitor(right, type_parameter_checker)) AttributeError: 'NoneType' object has no attribute 'accept'
AttributeError
def __init__(self, operators: List[str], operands: List[Expression]) -> None: self.operators = operators self.operands = operands self.method_types = [] self.literal = min(o.literal for o in self.operands) self.literal_hash = ( (cast(Any, "Comparison"),) + tuple(operators) + tuple(o.literal_hash for o in operands) )
def __init__(self, operators: List[str], operands: List[Expression]) -> None: self.operators = operators self.operands = operands self.method_types = [] self.literal = min(o.literal for o in self.operands) self.literal_hash = ( ("Comparison",) + tuple(operators) + tuple(o.literal_hash for o in operands) )
https://github.com/python/mypy/issues/1289
Traceback (most recent call last): File "./scripts/mypy", line 6, in <module> main(__file__) File "mypy/mypy/main.py", line 50, in main type_check_only(sources, bin_dir, options) File "mypy/mypy/main.py", line 94, in type_check_only python_path=options.python_path) File "mypy/mypy/build.py", line 210, in build result = manager.process(initial_states) File "mypy/mypy/build.py", line 425, in process next.process() File "mypy/mypy/build.py", line 930, in process self.type_checker().visit_file(self.tree, self.tree.path) File "mypy/mypy/checker.py", line 409, in visit_file self.accept(d) File "mypy/mypy/checker.py", line 450, in accept typ = node.accept(self) File "mypy/mypy/nodes.py", line 707, in accept return visitor.visit_try_stmt(self) File "mypy/mypy/checker.py", line 1732, in visit_try_stmt self.accept(s.else_body) File "mypy/mypy/checker.py", line 450, in accept typ = node.accept(self) File "mypy/mypy/nodes.py", line 526, in accept return visitor.visit_block(self) File "mypy/mypy/checker.py", line 1113, in visit_block self.accept(s) File "mypy/mypy/checker.py", line 450, in accept typ = node.accept(self) File "mypy/mypy/nodes.py", line 382, in accept return visitor.visit_func_def(self) File "mypy/mypy/checker.py", line 594, in visit_func_def 'redefinition with type') File "mypy/mypy/checker.py", line 2117, in check_subtype if not is_subtype(subtype, supertype): File "mypy/mypy/subtypes.py", line 49, in is_subtype return left.accept(SubtypeVisitor(right, type_parameter_checker)) AttributeError: 'NoneType' object has no attribute 'accept'
AttributeError
def __init__(self, items: List[Expression]) -> None: self.items = items if all(x.literal == LITERAL_YES for x in items): self.literal = LITERAL_YES self.literal_hash = (cast(Any, "List"),) + tuple(x.literal_hash for x in items)
def __init__(self, items: List[Expression]) -> None: self.items = items if all(x.literal == LITERAL_YES for x in items): self.literal = LITERAL_YES self.literal_hash = ("List",) + tuple(x.literal_hash for x in items)
https://github.com/python/mypy/issues/1289
Traceback (most recent call last): File "./scripts/mypy", line 6, in <module> main(__file__) File "mypy/mypy/main.py", line 50, in main type_check_only(sources, bin_dir, options) File "mypy/mypy/main.py", line 94, in type_check_only python_path=options.python_path) File "mypy/mypy/build.py", line 210, in build result = manager.process(initial_states) File "mypy/mypy/build.py", line 425, in process next.process() File "mypy/mypy/build.py", line 930, in process self.type_checker().visit_file(self.tree, self.tree.path) File "mypy/mypy/checker.py", line 409, in visit_file self.accept(d) File "mypy/mypy/checker.py", line 450, in accept typ = node.accept(self) File "mypy/mypy/nodes.py", line 707, in accept return visitor.visit_try_stmt(self) File "mypy/mypy/checker.py", line 1732, in visit_try_stmt self.accept(s.else_body) File "mypy/mypy/checker.py", line 450, in accept typ = node.accept(self) File "mypy/mypy/nodes.py", line 526, in accept return visitor.visit_block(self) File "mypy/mypy/checker.py", line 1113, in visit_block self.accept(s) File "mypy/mypy/checker.py", line 450, in accept typ = node.accept(self) File "mypy/mypy/nodes.py", line 382, in accept return visitor.visit_func_def(self) File "mypy/mypy/checker.py", line 594, in visit_func_def 'redefinition with type') File "mypy/mypy/checker.py", line 2117, in check_subtype if not is_subtype(subtype, supertype): File "mypy/mypy/subtypes.py", line 49, in is_subtype return left.accept(SubtypeVisitor(right, type_parameter_checker)) AttributeError: 'NoneType' object has no attribute 'accept'
AttributeError
def __init__(self, items: List[Tuple[Expression, Expression]]) -> None: self.items = items # key is None for **item, e.g. {'a': 1, **x} has # keys ['a', None] and values [1, x]. if all( x[0] and x[0].literal == LITERAL_YES and x[1].literal == LITERAL_YES for x in items ): self.literal = LITERAL_YES self.literal_hash = (cast(Any, "Dict"),) + tuple( (x[0].literal_hash, x[1].literal_hash) for x in items )
def __init__(self, items: List[Tuple[Expression, Expression]]) -> None: self.items = items # key is None for **item, e.g. {'a': 1, **x} has # keys ['a', None] and values [1, x]. if all( x[0] and x[0].literal == LITERAL_YES and x[1].literal == LITERAL_YES for x in items ): self.literal = LITERAL_YES self.literal_hash = ("Dict",) + tuple( (x[0].literal_hash, x[1].literal_hash) for x in items ) # type: ignore
https://github.com/python/mypy/issues/1289
Traceback (most recent call last): File "./scripts/mypy", line 6, in <module> main(__file__) File "mypy/mypy/main.py", line 50, in main type_check_only(sources, bin_dir, options) File "mypy/mypy/main.py", line 94, in type_check_only python_path=options.python_path) File "mypy/mypy/build.py", line 210, in build result = manager.process(initial_states) File "mypy/mypy/build.py", line 425, in process next.process() File "mypy/mypy/build.py", line 930, in process self.type_checker().visit_file(self.tree, self.tree.path) File "mypy/mypy/checker.py", line 409, in visit_file self.accept(d) File "mypy/mypy/checker.py", line 450, in accept typ = node.accept(self) File "mypy/mypy/nodes.py", line 707, in accept return visitor.visit_try_stmt(self) File "mypy/mypy/checker.py", line 1732, in visit_try_stmt self.accept(s.else_body) File "mypy/mypy/checker.py", line 450, in accept typ = node.accept(self) File "mypy/mypy/nodes.py", line 526, in accept return visitor.visit_block(self) File "mypy/mypy/checker.py", line 1113, in visit_block self.accept(s) File "mypy/mypy/checker.py", line 450, in accept typ = node.accept(self) File "mypy/mypy/nodes.py", line 382, in accept return visitor.visit_func_def(self) File "mypy/mypy/checker.py", line 594, in visit_func_def 'redefinition with type') File "mypy/mypy/checker.py", line 2117, in check_subtype if not is_subtype(subtype, supertype): File "mypy/mypy/subtypes.py", line 49, in is_subtype return left.accept(SubtypeVisitor(right, type_parameter_checker)) AttributeError: 'NoneType' object has no attribute 'accept'
AttributeError
def __init__(self, items: List[Expression]) -> None: self.items = items if all(x.literal == LITERAL_YES for x in items): self.literal = LITERAL_YES self.literal_hash = (cast(Any, "Tuple"),) + tuple(x.literal_hash for x in items)
def __init__(self, items: List[Expression]) -> None: self.items = items if all(x.literal == LITERAL_YES for x in items): self.literal = LITERAL_YES self.literal_hash = ("Tuple",) + tuple(x.literal_hash for x in items)
https://github.com/python/mypy/issues/1289
Traceback (most recent call last): File "./scripts/mypy", line 6, in <module> main(__file__) File "mypy/mypy/main.py", line 50, in main type_check_only(sources, bin_dir, options) File "mypy/mypy/main.py", line 94, in type_check_only python_path=options.python_path) File "mypy/mypy/build.py", line 210, in build result = manager.process(initial_states) File "mypy/mypy/build.py", line 425, in process next.process() File "mypy/mypy/build.py", line 930, in process self.type_checker().visit_file(self.tree, self.tree.path) File "mypy/mypy/checker.py", line 409, in visit_file self.accept(d) File "mypy/mypy/checker.py", line 450, in accept typ = node.accept(self) File "mypy/mypy/nodes.py", line 707, in accept return visitor.visit_try_stmt(self) File "mypy/mypy/checker.py", line 1732, in visit_try_stmt self.accept(s.else_body) File "mypy/mypy/checker.py", line 450, in accept typ = node.accept(self) File "mypy/mypy/nodes.py", line 526, in accept return visitor.visit_block(self) File "mypy/mypy/checker.py", line 1113, in visit_block self.accept(s) File "mypy/mypy/checker.py", line 450, in accept typ = node.accept(self) File "mypy/mypy/nodes.py", line 382, in accept return visitor.visit_func_def(self) File "mypy/mypy/checker.py", line 594, in visit_func_def 'redefinition with type') File "mypy/mypy/checker.py", line 2117, in check_subtype if not is_subtype(subtype, supertype): File "mypy/mypy/subtypes.py", line 49, in is_subtype return left.accept(SubtypeVisitor(right, type_parameter_checker)) AttributeError: 'NoneType' object has no attribute 'accept'
AttributeError
def __init__(self, items: List[Expression]) -> None: self.items = items if all(x.literal == LITERAL_YES for x in items): self.literal = LITERAL_YES self.literal_hash = (cast(Any, "Set"),) + tuple(x.literal_hash for x in items)
def __init__(self, items: List[Expression]) -> None: self.items = items if all(x.literal == LITERAL_YES for x in items): self.literal = LITERAL_YES self.literal_hash = ("Set",) + tuple(x.literal_hash for x in items)
https://github.com/python/mypy/issues/1289
Traceback (most recent call last): File "./scripts/mypy", line 6, in <module> main(__file__) File "mypy/mypy/main.py", line 50, in main type_check_only(sources, bin_dir, options) File "mypy/mypy/main.py", line 94, in type_check_only python_path=options.python_path) File "mypy/mypy/build.py", line 210, in build result = manager.process(initial_states) File "mypy/mypy/build.py", line 425, in process next.process() File "mypy/mypy/build.py", line 930, in process self.type_checker().visit_file(self.tree, self.tree.path) File "mypy/mypy/checker.py", line 409, in visit_file self.accept(d) File "mypy/mypy/checker.py", line 450, in accept typ = node.accept(self) File "mypy/mypy/nodes.py", line 707, in accept return visitor.visit_try_stmt(self) File "mypy/mypy/checker.py", line 1732, in visit_try_stmt self.accept(s.else_body) File "mypy/mypy/checker.py", line 450, in accept typ = node.accept(self) File "mypy/mypy/nodes.py", line 526, in accept return visitor.visit_block(self) File "mypy/mypy/checker.py", line 1113, in visit_block self.accept(s) File "mypy/mypy/checker.py", line 450, in accept typ = node.accept(self) File "mypy/mypy/nodes.py", line 382, in accept return visitor.visit_func_def(self) File "mypy/mypy/checker.py", line 594, in visit_func_def 'redefinition with type') File "mypy/mypy/checker.py", line 2117, in check_subtype if not is_subtype(subtype, supertype): File "mypy/mypy/subtypes.py", line 49, in is_subtype return left.accept(SubtypeVisitor(right, type_parameter_checker)) AttributeError: 'NoneType' object has no attribute 'accept'
AttributeError
def __init__(self) -> None: # -- build options -- self.build_type = BuildType.STANDARD self.python_version = defaults.PYTHON3_VERSION self.platform = sys.platform self.custom_typing_module = None # type: str self.report_dirs = {} # type: Dict[str, str] self.silent_imports = False self.almost_silent = False # Disallow calling untyped functions from typed ones self.disallow_untyped_calls = False # Disallow defining untyped (or incompletely typed) functions self.disallow_untyped_defs = False # Type check unannotated functions self.check_untyped_defs = False # Disallow subclassing values of type 'Any' self.disallow_subclassing_any = False # Also check typeshed for missing annotations self.warn_incomplete_stub = False # Warn about casting an expression to its inferred type self.warn_redundant_casts = False # Warn about falling off the end of a function returning non-None self.warn_no_return = False # Warn about unused '# type: ignore' comments self.warn_unused_ignores = False # Apply strict None checking self.strict_optional = False # Files in which to allow strict-Optional related errors # TODO: Kill this in favor of show_none_errors self.strict_optional_whitelist = None # type: Optional[List[str]] # Alternate way to show/hide strict-None-checking related errors self.show_none_errors = True # Use script name instead of __main__ self.scripts_are_modules = False # Config file name self.config_file = None # type: Optional[str] # Per-file options (raw) self.per_file_options = {} # type: Dict[str, Dict[str, object]] # -- 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 # -- test options -- # Stop after the semantic analysis phase self.semantic_analysis_only = False # Use stub builtins fixtures to speed up tests self.use_builtins_fixtures = False # -- experimental options -- self.fast_parser = False self.incremental = False self.cache_dir = defaults.CACHE_DIR self.debug_cache = False self.hide_error_context = False # Hide "note: In function "foo":" messages. self.shadow_file = None # type: Optional[Tuple[str, str]] self.show_column_numbers = False # type: bool
def __init__(self) -> None: # -- build options -- self.build_type = BuildType.STANDARD self.python_version = defaults.PYTHON3_VERSION self.platform = sys.platform self.custom_typing_module = None # type: str self.report_dirs = {} # type: Dict[str, str] self.silent_imports = False self.almost_silent = False # Disallow calling untyped functions from typed ones self.disallow_untyped_calls = False # Disallow defining untyped (or incompletely typed) functions self.disallow_untyped_defs = False # Type check unannotated functions self.check_untyped_defs = False # Disallow subclassing values of type 'Any' self.disallow_subclassing_any = False # Also check typeshed for missing annotations self.warn_incomplete_stub = False # Warn about casting an expression to its inferred type self.warn_redundant_casts = False # Warn about unused '# type: ignore' comments self.warn_unused_ignores = False # Apply strict None checking self.strict_optional = False # Files in which to allow strict-Optional related errors # TODO: Kill this in favor of show_none_errors self.strict_optional_whitelist = None # type: Optional[List[str]] # Alternate way to show/hide strict-None-checking related errors self.show_none_errors = True # Use script name instead of __main__ self.scripts_are_modules = False # Config file name self.config_file = None # type: Optional[str] # Per-file options (raw) self.per_file_options = {} # type: Dict[str, Dict[str, object]] # -- 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 # -- test options -- # Stop after the semantic analysis phase self.semantic_analysis_only = False # Use stub builtins fixtures to speed up tests self.use_builtins_fixtures = False # -- experimental options -- self.fast_parser = False self.incremental = False self.cache_dir = defaults.CACHE_DIR self.debug_cache = False self.hide_error_context = False # Hide "note: In function "foo":" messages. self.shadow_file = None # type: Optional[Tuple[str, str]] self.show_column_numbers = False # type: bool
https://github.com/python/mypy/issues/1289
Traceback (most recent call last): File "./scripts/mypy", line 6, in <module> main(__file__) File "mypy/mypy/main.py", line 50, in main type_check_only(sources, bin_dir, options) File "mypy/mypy/main.py", line 94, in type_check_only python_path=options.python_path) File "mypy/mypy/build.py", line 210, in build result = manager.process(initial_states) File "mypy/mypy/build.py", line 425, in process next.process() File "mypy/mypy/build.py", line 930, in process self.type_checker().visit_file(self.tree, self.tree.path) File "mypy/mypy/checker.py", line 409, in visit_file self.accept(d) File "mypy/mypy/checker.py", line 450, in accept typ = node.accept(self) File "mypy/mypy/nodes.py", line 707, in accept return visitor.visit_try_stmt(self) File "mypy/mypy/checker.py", line 1732, in visit_try_stmt self.accept(s.else_body) File "mypy/mypy/checker.py", line 450, in accept typ = node.accept(self) File "mypy/mypy/nodes.py", line 526, in accept return visitor.visit_block(self) File "mypy/mypy/checker.py", line 1113, in visit_block self.accept(s) File "mypy/mypy/checker.py", line 450, in accept typ = node.accept(self) File "mypy/mypy/nodes.py", line 382, in accept return visitor.visit_func_def(self) File "mypy/mypy/checker.py", line 594, in visit_func_def 'redefinition with type') File "mypy/mypy/checker.py", line 2117, in check_subtype if not is_subtype(subtype, supertype): File "mypy/mypy/subtypes.py", line 49, in is_subtype return left.accept(SubtypeVisitor(right, type_parameter_checker)) AttributeError: 'NoneType' object has no attribute 'accept'
AttributeError
def map_instance_to_supertypes( instance: Instance, supertype: TypeInfo ) -> List[Instance]: # FIX: Currently we should only have one supertype per interface, so no # need to return an array result = [] # type: List[Instance] for path in class_derivation_paths(instance.type, supertype): types = [instance] for sup in path: a = [] # type: List[Instance] for t in types: a.extend(map_instance_to_direct_supertypes(t, sup)) types = a result.extend(types) if result: return result else: # Nothing. Presumably due to an error. Construct a dummy using Any. return [Instance(supertype, [AnyType()] * len(supertype.type_vars))]
def map_instance_to_supertypes( instance: Instance, supertype: TypeInfo ) -> List[Instance]: # FIX: Currently we should only have one supertype per interface, so no # need to return an array result = [] # type: List[Instance] for path in class_derivation_paths(instance.type, supertype): types = [instance] for sup in path: a = [] # type: List[Instance] for t in types: a.extend(map_instance_to_direct_supertypes(t, sup)) types = a result.extend(types) return result
https://github.com/python/mypy/issues/2244
t_test6.py:1: error: Invalid base class t_test6.py:5: error: INTERNAL ERROR -- please report a bug at https://github.com/python/mypy/issues Traceback (most recent call last): File "/usr/local/bin/mypy", line 6, in <module> main(__file__) File "/usr/local/lib/python3.4/dist-packages/mypy/main.py", line 38, in main res = type_check_only(sources, bin_dir, options) File "/usr/local/lib/python3.4/dist-packages/mypy/main.py", line 79, in type_check_only options=options) File "/usr/local/lib/python3.4/dist-packages/mypy/build.py", line 181, in build dispatch(sources, manager) File "/usr/local/lib/python3.4/dist-packages/mypy/build.py", line 1470, in dispatch process_graph(graph, manager) File "/usr/local/lib/python3.4/dist-packages/mypy/build.py", line 1650, in process_graph process_stale_scc(graph, scc) File "/usr/local/lib/python3.4/dist-packages/mypy/build.py", line 1729, in process_stale_scc graph[id].type_check() File "/usr/local/lib/python3.4/dist-packages/mypy/build.py", line 1415, in type_check manager.type_checker.visit_file(self.tree, self.xpath, self.options) File "/usr/local/lib/python3.4/dist-packages/mypy/checker.py", line 165, in visit_file self.accept(d) File "/usr/local/lib/python3.4/dist-packages/mypy/checker.py", line 217, in accept typ = node.accept(self) File "/usr/local/lib/python3.4/dist-packages/mypy/nodes.py", line 796, in accept return visitor.visit_assignment_stmt(self) File "/usr/local/lib/python3.4/dist-packages/mypy/checker.py", line 1028, in visit_assignment_stmt self.check_assignment(s.lvalues[-1], s.rvalue, s.type is None, s.new_syntax) File "/usr/local/lib/python3.4/dist-packages/mypy/checker.py", line 1044, in check_assignment infer_lvalue_type) File "/usr/local/lib/python3.4/dist-packages/mypy/checker.py", line 1129, in check_assignment_to_multiple_lvalues self.check_multi_assignment(lvalues, rvalue, context, infer_lvalue_type) File "/usr/local/lib/python3.4/dist-packages/mypy/checker.py", line 1165, in check_multi_assignment context, infer_lvalue_type) File "/usr/local/lib/python3.4/dist-packages/mypy/checker.py", line 1257, in check_multi_assignment_from_iterable item_type = self.iterable_item_type(cast(Instance, rvalue_type)) File "/usr/local/lib/python3.4/dist-packages/mypy/checker.py", line 2321, in iterable_item_type self.lookup_typeinfo('typing.Iterable')) File "/usr/local/lib/python3.4/dist-packages/mypy/maptype.py", line 23, in map_instance_to_supertype return map_instance_to_supertypes(instance, superclass)[0] IndexError: list index out of range t_test6.py:5: note: use --pdb to drop into pdb
IndexError
def analyze_class_attribute_access( itype: Instance, name: str, context: Context, is_lvalue: bool, builtin_type: Callable[[str], Instance], not_ready_callback: Callable[[str, Context], None], msg: MessageBuilder, ) -> Type: node = itype.type.get(name) if not node: if itype.type.fallback_to_any: return AnyType() return None is_decorated = isinstance(node.node, Decorator) is_method = is_decorated or isinstance(node.node, FuncDef) if is_lvalue: if is_method: msg.cant_assign_to_method(context) if isinstance(node.node, TypeInfo): msg.fail(messages.CANNOT_ASSIGN_TO_TYPE, context) if itype.type.is_enum and not (is_lvalue or is_decorated or is_method): return itype t = node.type if t: if isinstance(t, PartialType): return handle_partial_attribute_type(t, is_lvalue, msg, node.node) is_classmethod = is_decorated and cast(Decorator, node.node).func.is_class return add_class_tvars(t, itype.type, is_classmethod, builtin_type) elif isinstance(node.node, Var): not_ready_callback(name, context) return AnyType() if isinstance(node.node, TypeInfo): return type_object_type(node.node, builtin_type) if isinstance(node.node, MypyFile): # Reference to a module object. return builtin_type("builtins.module") if is_decorated: # TODO: Return type of decorated function. This is quick hack to work around #998. return AnyType() else: return function_type( cast(FuncBase, node.node), builtin_type("builtins.function") )
def analyze_class_attribute_access( itype: Instance, name: str, context: Context, is_lvalue: bool, builtin_type: Callable[[str], Instance], not_ready_callback: Callable[[str, Context], None], msg: MessageBuilder, ) -> Type: node = itype.type.get(name) if not node: if itype.type.fallback_to_any: return AnyType() return None is_decorated = isinstance(node.node, Decorator) is_method = is_decorated or isinstance(node.node, FuncDef) if is_lvalue: if is_method: msg.cant_assign_to_method(context) if isinstance(node.node, TypeInfo): msg.fail(messages.CANNOT_ASSIGN_TO_TYPE, context) if itype.type.is_enum and not (is_lvalue or is_decorated or is_method): return itype t = node.type if t: if isinstance(t, PartialType): return handle_partial_attribute_type(t, is_lvalue, msg, node.node) is_classmethod = is_decorated and cast(Decorator, node.node).func.is_class return add_class_tvars(t, itype.type, is_classmethod, builtin_type) elif isinstance(node.node, Var): not_ready_callback(name, context) return AnyType() if isinstance(node.node, TypeInfo): return type_object_type(node.node, builtin_type) if is_decorated: # TODO: Return type of decorated function. This is quick hack to work around #998. return AnyType() else: return function_type( cast(FuncBase, node.node), builtin_type("builtins.function") )
https://github.com/python/mypy/issues/1839
Traceback (most recent call last): File "C:\Users\fred\Anaconda3\Scripts\mypy", line 6, in <module> main(__file__) File "C:\Users\fred\Anaconda3\lib\site-packages\mypy\main.py", line 54, in main res = type_check_only(sources, bin_dir, options) File "C:\Users\fred\Anaconda3\lib\site-packages\mypy\main.py", line 102, in type_check_only python_path=options.python_path) File "C:\Users\fred\Anaconda3\lib\site-packages\mypy\build.py", line 211, in build dispatch(sources, manager) File "C:\Users\fred\Anaconda3\lib\site-packages\mypy\build.py", line 1336, in dispatch process_graph(graph, manager) File "C:\Users\fred\Anaconda3\lib\site-packages\mypy\build.py", line 1467, in process_graph process_stale_scc(graph, scc) File "C:\Users\fred\Anaconda3\lib\site-packages\mypy\build.py", line 1497, in process_stale_scc graph[id].type_check() File "C:\Users\fred\Anaconda3\lib\site-packages\mypy\build.py", line 1316, in type_check manager.type_checker.visit_file(self.tree, self.xpath) File "C:\Users\fred\Anaconda3\lib\site-packages\mypy\checker.py", line 426, in visit_file self.accept(d) File "C:\Users\fred\Anaconda3\lib\site-packages\mypy\checker.py", line 476, in accept typ = node.accept(self) File "C:\Users\fred\Anaconda3\lib\site-packages\mypy\nodes.py", line 531, in accept return visitor.visit_decorator(self) File "C:\Users\fred\Anaconda3\lib\site-packages\mypy\checker.py", line 1956, in visit_decorator dec = self.accept(d) File "C:\Users\fred\Anaconda3\lib\site-packages\mypy\checker.py", line 476, in accept typ = node.accept(self) File "C:\Users\fred\Anaconda3\lib\site-packages\mypy\nodes.py", line 1185, in accept return visitor.visit_call_expr(self) File "C:\Users\fred\Anaconda3\lib\site-packages\mypy\checker.py", line 2009, in visit_call_expr return self.expr_checker.visit_call_expr(e) File "C:\Users\fred\Anaconda3\lib\site-packages\mypy\checkexpr.py", line 135, in visit_call_expr callee_type = self.accept(e.callee) File "C:\Users\fred\Anaconda3\lib\site-packages\mypy\checkexpr.py", line 1531, in accept return self.chk.accept(node, context) File "C:\Users\fred\Anaconda3\lib\site-packages\mypy\checker.py", line 476, in accept typ = node.accept(self) File "C:\Users\fred\Anaconda3\lib\site-packages\mypy\nodes.py", line 1141, in accept return visitor.visit_member_expr(self) File "C:\Users\fred\Anaconda3\lib\site-packages\mypy\checker.py", line 2053, in visit_member_expr return self.expr_checker.visit_member_expr(e) File "C:\Users\fred\Anaconda3\lib\site-packages\mypy\checkexpr.py", line 836, in visit_member_expr result = self.analyze_ordinary_member_access(e, False) File "C:\Users\fred\Anaconda3\lib\site-packages\mypy\checkexpr.py", line 847, in analyze_ordinary_member_access return analyze_member_access(e.name, self.accept(e.expr), e, File "C:\Users\fred\Anaconda3\lib\site-packages\mypy\checkexpr.py", line 1531, in accept return self.chk.accept(node, context) File "C:\Users\fred\Anaconda3\lib\site-packages\mypy\checker.py", line 476, in accept typ = node.accept(self) File "C:\Users\fred\Anaconda3\lib\site-packages\mypy\nodes.py", line 1141, in accept return visitor.visit_member_expr(self) File "C:\Users\fred\Anaconda3\lib\site-packages\mypy\checker.py", line 2053, in visit_member_expr return self.expr_checker.visit_member_expr(e) File "C:\Users\fred\Anaconda3\lib\site-packages\mypy\checkexpr.py", line 836, in visit_member_expr result = self.analyze_ordinary_member_access(e, False) File "C:\Users\fred\Anaconda3\lib\site-packages\mypy\checkexpr.py", line 849, in analyze_ordinary_member_access self.named_type, self.not_ready_callback, self.msg) File "C:\Users\fred\Anaconda3\lib\site-packages\mypy\checkmember.py", line 96, in analyze_member_access builtin_type, not_ready_callback, msg) File "C:\Users\fred\Anaconda3\lib\site-packages\mypy\checkmember.py", line 319, in analyze_class_attribute_access return function_type(cast(FuncBase, node.node), builtin_type('builtins.function')) File "C:\Users\fred\Anaconda3\lib\site-packages\mypy\nodes.py", line 2129, in function_type if func.type: AttributeError: 'MypyFile' object has no attribute 'type'
AttributeError
def visit_member_expr(self, expr: MemberExpr) -> None: base = expr.expr base.accept(self) # Bind references to module attributes. if isinstance(base, RefExpr) and base.kind == MODULE_REF: # This branch handles the case foo.bar where foo is a module. # In this case base.node is the module's MypyFile and we look up # bar in its namespace. This must be done for all types of bar. file = cast(MypyFile, base.node) n = file.names.get(expr.name, None) if file is not None else None if n: n = self.normalize_type_alias(n, expr) if not n: return expr.kind = n.kind expr.fullname = n.fullname expr.node = n.node else: # We only catch some errors here; the rest will be # catched during type checking. # # This way we can report a larger number of errors in # one type checker run. If we reported errors here, # the build would terminate after semantic analysis # and we wouldn't be able to report any type errors. full_name = "%s.%s" % ( file.fullname() if file is not None else None, expr.name, ) if full_name in obsolete_name_mapping: self.fail( "Module has no attribute %r (it's now called %r)" % (expr.name, obsolete_name_mapping[full_name]), expr, ) elif isinstance(base, RefExpr) and isinstance(base.node, TypeInfo): # This branch handles the case C.bar where C is a class # and bar is a module resulting from `import bar` inside # class C. Here base.node is a TypeInfo, and again we # look up the name in its namespace. This is done only # when bar is a module; other things (e.g. methods) # are handled by other code in checkmember. n = base.node.names.get(expr.name) if n is not None and n.kind == MODULE_REF: n = self.normalize_type_alias(n, expr) if not n: return expr.kind = n.kind expr.fullname = n.fullname expr.node = n.node
def visit_member_expr(self, expr: MemberExpr) -> None: base = expr.expr base.accept(self) # Bind references to module attributes. if isinstance(base, RefExpr) and base.kind == MODULE_REF: file = cast(MypyFile, base.node) n = file.names.get(expr.name, None) if file is not None else None if n: n = self.normalize_type_alias(n, expr) if not n: return expr.kind = n.kind expr.fullname = n.fullname expr.node = n.node else: # We only catch some errors here; the rest will be # catched during type checking. # # This way we can report a larger number of errors in # one type checker run. If we reported errors here, # the build would terminate after semantic analysis # and we wouldn't be able to report any type errors. full_name = "%s.%s" % ( file.fullname() if file is not None else None, expr.name, ) if full_name in obsolete_name_mapping: self.fail( "Module has no attribute %r (it's now called %r)" % (expr.name, obsolete_name_mapping[full_name]), expr, )
https://github.com/python/mypy/issues/1839
Traceback (most recent call last): File "C:\Users\fred\Anaconda3\Scripts\mypy", line 6, in <module> main(__file__) File "C:\Users\fred\Anaconda3\lib\site-packages\mypy\main.py", line 54, in main res = type_check_only(sources, bin_dir, options) File "C:\Users\fred\Anaconda3\lib\site-packages\mypy\main.py", line 102, in type_check_only python_path=options.python_path) File "C:\Users\fred\Anaconda3\lib\site-packages\mypy\build.py", line 211, in build dispatch(sources, manager) File "C:\Users\fred\Anaconda3\lib\site-packages\mypy\build.py", line 1336, in dispatch process_graph(graph, manager) File "C:\Users\fred\Anaconda3\lib\site-packages\mypy\build.py", line 1467, in process_graph process_stale_scc(graph, scc) File "C:\Users\fred\Anaconda3\lib\site-packages\mypy\build.py", line 1497, in process_stale_scc graph[id].type_check() File "C:\Users\fred\Anaconda3\lib\site-packages\mypy\build.py", line 1316, in type_check manager.type_checker.visit_file(self.tree, self.xpath) File "C:\Users\fred\Anaconda3\lib\site-packages\mypy\checker.py", line 426, in visit_file self.accept(d) File "C:\Users\fred\Anaconda3\lib\site-packages\mypy\checker.py", line 476, in accept typ = node.accept(self) File "C:\Users\fred\Anaconda3\lib\site-packages\mypy\nodes.py", line 531, in accept return visitor.visit_decorator(self) File "C:\Users\fred\Anaconda3\lib\site-packages\mypy\checker.py", line 1956, in visit_decorator dec = self.accept(d) File "C:\Users\fred\Anaconda3\lib\site-packages\mypy\checker.py", line 476, in accept typ = node.accept(self) File "C:\Users\fred\Anaconda3\lib\site-packages\mypy\nodes.py", line 1185, in accept return visitor.visit_call_expr(self) File "C:\Users\fred\Anaconda3\lib\site-packages\mypy\checker.py", line 2009, in visit_call_expr return self.expr_checker.visit_call_expr(e) File "C:\Users\fred\Anaconda3\lib\site-packages\mypy\checkexpr.py", line 135, in visit_call_expr callee_type = self.accept(e.callee) File "C:\Users\fred\Anaconda3\lib\site-packages\mypy\checkexpr.py", line 1531, in accept return self.chk.accept(node, context) File "C:\Users\fred\Anaconda3\lib\site-packages\mypy\checker.py", line 476, in accept typ = node.accept(self) File "C:\Users\fred\Anaconda3\lib\site-packages\mypy\nodes.py", line 1141, in accept return visitor.visit_member_expr(self) File "C:\Users\fred\Anaconda3\lib\site-packages\mypy\checker.py", line 2053, in visit_member_expr return self.expr_checker.visit_member_expr(e) File "C:\Users\fred\Anaconda3\lib\site-packages\mypy\checkexpr.py", line 836, in visit_member_expr result = self.analyze_ordinary_member_access(e, False) File "C:\Users\fred\Anaconda3\lib\site-packages\mypy\checkexpr.py", line 847, in analyze_ordinary_member_access return analyze_member_access(e.name, self.accept(e.expr), e, File "C:\Users\fred\Anaconda3\lib\site-packages\mypy\checkexpr.py", line 1531, in accept return self.chk.accept(node, context) File "C:\Users\fred\Anaconda3\lib\site-packages\mypy\checker.py", line 476, in accept typ = node.accept(self) File "C:\Users\fred\Anaconda3\lib\site-packages\mypy\nodes.py", line 1141, in accept return visitor.visit_member_expr(self) File "C:\Users\fred\Anaconda3\lib\site-packages\mypy\checker.py", line 2053, in visit_member_expr return self.expr_checker.visit_member_expr(e) File "C:\Users\fred\Anaconda3\lib\site-packages\mypy\checkexpr.py", line 836, in visit_member_expr result = self.analyze_ordinary_member_access(e, False) File "C:\Users\fred\Anaconda3\lib\site-packages\mypy\checkexpr.py", line 849, in analyze_ordinary_member_access self.named_type, self.not_ready_callback, self.msg) File "C:\Users\fred\Anaconda3\lib\site-packages\mypy\checkmember.py", line 96, in analyze_member_access builtin_type, not_ready_callback, msg) File "C:\Users\fred\Anaconda3\lib\site-packages\mypy\checkmember.py", line 319, in analyze_class_attribute_access return function_type(cast(FuncBase, node.node), builtin_type('builtins.function')) File "C:\Users\fred\Anaconda3\lib\site-packages\mypy\nodes.py", line 2129, in function_type if func.type: AttributeError: 'MypyFile' object has no attribute 'type'
AttributeError
def load_graph(sources: List[BuildSource], manager: BuildManager) -> Graph: """Given some source files, load the full dependency graph.""" graph = {} # type: Graph # The deque is used to implement breadth-first traversal. # 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] # Seed the graph with the initial root sources. for bs in sources: try: st = State(id=bs.module, path=bs.path, source=bs.text, manager=manager) except ModuleNotFound: continue if st.id in graph: manager.errors.set_file(st.xpath) manager.errors.report(-1, "Duplicate module named '%s'" % st.id) manager.errors.raise_error() graph[st.id] = st new.append(st) # Collect dependencies. We go breadth-first. while new: st = new.popleft() for dep in st.ancestors + st.dependencies + st.suppressed: if dep not in graph: try: if dep in st.ancestors: # TODO: Why not 'if dep not in st.dependencies' ? # Ancestors don't have import context. newst = State( id=dep, path=None, source=None, manager=manager, ancestor_for=st, ) else: newst = State( id=dep, path=None, source=None, manager=manager, caller_state=st, caller_line=st.dep_line_map.get(dep, 1), ) except ModuleNotFound: if dep in st.dependencies: st.dependencies.remove(dep) st.suppressed.append(dep) else: assert newst.id not in graph, newst.id graph[newst.id] = newst 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() return graph
def load_graph(sources: List[BuildSource], manager: BuildManager) -> Graph: """Given some source files, load the full dependency graph.""" graph = {} # type: Graph # The deque is used to implement breadth-first traversal. # 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] # Seed the graph with the initial root sources. for bs in sources: try: st = State(id=bs.module, path=bs.path, source=bs.text, manager=manager) except ModuleNotFound: continue if st.id in graph: manager.errors.set_file(st.xpath) manager.errors.report(-1, "Duplicate module named '%s'" % st.id) manager.errors.raise_error() graph[st.id] = st new.append(st) # Collect dependencies. We go breadth-first. while new: st = new.popleft() for dep in st.ancestors + st.dependencies: if dep not in graph: try: if dep in st.ancestors: # TODO: Why not 'if dep not in st.dependencies' ? # Ancestors don't have import context. newst = State( id=dep, path=None, source=None, manager=manager, ancestor_for=st, ) else: newst = State( id=dep, path=None, source=None, manager=manager, caller_state=st, caller_line=st.dep_line_map.get(dep, 1), ) except ModuleNotFound: if dep in st.dependencies: st.dependencies.remove(dep) st.suppressed.append(dep) else: assert newst.id not in graph, newst.id graph[newst.id] = newst new.append(newst) if dep in st.ancestors and dep in graph: graph[dep].child_modules.add(st.id) for id, g in graph.items(): if g.has_new_submodules(): g.parse_file() return graph
https://github.com/python/mypy/issues/2017
testdir/main.py:4: error: INTERNAL ERROR -- please report a bug at https://github.com/python/mypy/issues Traceback (most recent call last): File "/usr/local/Cellar/python3/3.5.2/Frameworks/Python.framework/Versions/3.5/lib/python3.5/runpy.py", line 184, in _run_module_as_main "__main__", mod_spec) File "/usr/local/Cellar/python3/3.5.2/Frameworks/Python.framework/Versions/3.5/lib/python3.5/runpy.py", line 85, in _run_code exec(code, run_globals) File "/Users/me/ve/35/lib/python3.5/site-packages/mypy/__main__.py", line 5, in <module> main(None) File "/Users/me/ve/35/lib/python3.5/site-packages/mypy/main.py", line 40, in main res = type_check_only(sources, bin_dir, options) File "/Users/me/ve/35/lib/python3.5/site-packages/mypy/main.py", line 81, in type_check_only options=options) File "/Users/me/ve/35/lib/python3.5/site-packages/mypy/build.py", line 180, in build dispatch(sources, manager) File "/Users/me/ve/35/lib/python3.5/site-packages/mypy/build.py", line 1335, in dispatch process_graph(graph, manager) File "/Users/me/ve/35/lib/python3.5/site-packages/mypy/build.py", line 1478, in process_graph process_stale_scc(graph, scc) File "/Users/me/ve/35/lib/python3.5/site-packages/mypy/build.py", line 1555, in process_stale_scc graph[id].type_check() File "/Users/me/ve/35/lib/python3.5/site-packages/mypy/build.py", line 1313, in type_check manager.type_checker.visit_file(self.tree, self.xpath) File "/Users/me/ve/35/lib/python3.5/site-packages/mypy/checker.py", line 152, in visit_file self.accept(d) File "/Users/me/ve/35/lib/python3.5/site-packages/mypy/checker.py", line 201, in accept typ = node.accept(self) File "/Users/me/ve/35/lib/python3.5/site-packages/mypy/nodes.py", line 477, in accept return visitor.visit_func_def(self) File "/Users/me/ve/35/lib/python3.5/site-packages/mypy/checker.py", line 408, in visit_func_def self.check_func_item(defn, name=defn.name()) File "/Users/me/ve/35/lib/python3.5/site-packages/mypy/checker.py", line 471, in check_func_item self.check_func_def(defn, typ, name) File "/Users/me/ve/35/lib/python3.5/site-packages/mypy/checker.py", line 591, in check_func_def self.accept(item.body) File "/Users/me/ve/35/lib/python3.5/site-packages/mypy/checker.py", line 201, in accept typ = node.accept(self) File "/Users/me/ve/35/lib/python3.5/site-packages/mypy/nodes.py", line 727, in accept return visitor.visit_block(self) File "/Users/me/ve/35/lib/python3.5/site-packages/mypy/checker.py", line 999, in visit_block self.accept(s) File "/Users/me/ve/35/lib/python3.5/site-packages/mypy/checker.py", line 201, in accept typ = node.accept(self) File "/Users/me/ve/35/lib/python3.5/site-packages/mypy/nodes.py", line 741, in accept return visitor.visit_expression_stmt(self) File "/Users/me/ve/35/lib/python3.5/site-packages/mypy/checker.py", line 1437, in visit_expression_stmt self.accept(s.expr) File "/Users/me/ve/35/lib/python3.5/site-packages/mypy/checker.py", line 201, in accept typ = node.accept(self) File "/Users/me/ve/35/lib/python3.5/site-packages/mypy/nodes.py", line 1157, in accept return visitor.visit_member_expr(self) File "/Users/me/ve/35/lib/python3.5/site-packages/mypy/checker.py", line 1978, in visit_member_expr return self.expr_checker.visit_member_expr(e) File "/Users/me/ve/35/lib/python3.5/site-packages/mypy/checkexpr.py", line 861, in visit_member_expr result = self.analyze_ordinary_member_access(e, False) File "/Users/me/ve/35/lib/python3.5/site-packages/mypy/checkexpr.py", line 874, in analyze_ordinary_member_access self.named_type, self.not_ready_callback, self.msg) File "/Users/me/ve/35/lib/python3.5/site-packages/mypy/checkmember.py", line 77, in analyze_member_access report_type=report_type) File "/Users/me/ve/35/lib/python3.5/site-packages/mypy/checkmember.py", line 174, in analyze_member_var_access v = lookup_member_var_or_accessor(info, name, is_lvalue) File "/Users/me/ve/35/lib/python3.5/site-packages/mypy/checkmember.py", line 267, in lookup_member_var_or_accessor node = info.get(name) File "/Users/me/ve/35/lib/python3.5/site-packages/mypy/nodes.py", line 1853, in get for cls in self.mro: TypeError: 'NoneType' object is not iterable testdir/main.py:4: note: use --pdb to drop into pdb
TypeError
def visit_type_var(self, t: TypeVarType) -> Type: return t
def visit_type_var(self, t: TypeVarType) -> Type: raise RuntimeError("TypeVarType is already analyzed")
https://github.com/python/mypy/issues/1898
*** INTERNAL ERROR *** asd4.py:7: error: Internal error -- please report a bug at https://github.com/python/mypy/issues NOTE: you can use "mypy --pdb ..." to drop into the debugger when this happens. Traceback (most recent call last): File "/usr/lib/python-exec/python3.4/mypy", line 6, in <module> main(__file__) File "/usr/lib64/python3.4/site-packages/mypy/main.py", line 40, in main res = type_check_only(sources, bin_dir, options) File "/usr/lib64/python3.4/site-packages/mypy/main.py", line 81, in type_check_only options=options) File "/usr/lib64/python3.4/site-packages/mypy/build.py", line 177, in build dispatch(sources, manager) File "/usr/lib64/python3.4/site-packages/mypy/build.py", line 1331, in dispatch process_graph(graph, manager) File "/usr/lib64/python3.4/site-packages/mypy/build.py", line 1469, in process_graph process_stale_scc(graph, scc) File "/usr/lib64/python3.4/site-packages/mypy/build.py", line 1542, in process_stale_scc graph[id].semantic_analysis() File "/usr/lib64/python3.4/site-packages/mypy/build.py", line 1296, in semantic_analysis self.manager.semantic_analyzer.visit_file(self.tree, self.xpath) File "/usr/lib64/python3.4/site-packages/mypy/semanal.py", line 243, in visit_file self.accept(d) File "/usr/lib64/python3.4/site-packages/mypy/semanal.py", line 2306, in accept node.accept(self) File "/usr/lib64/python3.4/site-packages/mypy/nodes.py", line 660, in accept return visitor.visit_class_def(self) File "/usr/lib64/python3.4/site-packages/mypy/semanal.py", line 564, in visit_class_def defn.defs.accept(self) File "/usr/lib64/python3.4/site-packages/mypy/nodes.py", line 723, in accept return visitor.visit_block(self) File "/usr/lib64/python3.4/site-packages/mypy/semanal.py", line 1014, in visit_block self.accept(s) File "/usr/lib64/python3.4/site-packages/mypy/semanal.py", line 2306, in accept node.accept(self) File "/usr/lib64/python3.4/site-packages/mypy/nodes.py", line 544, in accept return visitor.visit_decorator(self) File "/usr/lib64/python3.4/site-packages/mypy/semanal.py", line 1626, in visit_decorator dec.func.accept(self) File "/usr/lib64/python3.4/site-packages/mypy/nodes.py", line 475, in accept return visitor.visit_func_def(self) File "/usr/lib64/python3.4/site-packages/mypy/semanal.py", line 316, in visit_func_def self.analyze_function(defn) File "/usr/lib64/python3.4/site-packages/mypy/semanal.py", line 468, in analyze_function defn.type = self.anal_type(defn.type) File "/usr/lib64/python3.4/site-packages/mypy/semanal.py", line 1039, in anal_type return t.accept(a) File "/usr/lib64/python3.4/site-packages/mypy/types.py", line 606, in accept return visitor.visit_callable_type(self) File "/usr/lib64/python3.4/site-packages/mypy/typeanal.py", line 204, in visit_callable_type return t.copy_modified(arg_types=self.anal_array(t.arg_types), File "/usr/lib64/python3.4/site-packages/mypy/typeanal.py", line 274, in anal_array res.append(t.accept(self)) File "/usr/lib64/python3.4/site-packages/mypy/types.py", line 606, in accept return visitor.visit_callable_type(self) File "/usr/lib64/python3.4/site-packages/mypy/typeanal.py", line 204, in visit_callable_type return t.copy_modified(arg_types=self.anal_array(t.arg_types), File "/usr/lib64/python3.4/site-packages/mypy/typeanal.py", line 274, in anal_array res.append(t.accept(self)) File "/usr/lib64/python3.4/site-packages/mypy/types.py", line 448, in accept return visitor.visit_type_var(self) File "/usr/lib64/python3.4/site-packages/mypy/typeanal.py", line 201, in visit_type_var raise RuntimeError('TypeVarType is already analyzed') RuntimeError: TypeVarType is already analyzed
RuntimeError
def check_method_override_for_base_with_name( self, defn: FuncBase, name: str, base: TypeInfo ) -> None: base_attr = base.names.get(name) if base_attr: # The name of the method is defined in the base class. # Construct the type of the overriding method. typ = self.method_type(defn) # 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: 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), defn.info, base ) # Check that the types are compatible. # TODO overloaded signatures self.check_override( typ, cast(FunctionLike, original), defn.name(), name, base.name(), defn ) else: self.msg.signature_incompatible_with_supertype( defn.name(), name, base.name(), defn )
def check_method_override_for_base_with_name( self, defn: FuncBase, name: str, base: TypeInfo ) -> None: base_attr = base.names.get(name) if base_attr: # The name of the method is defined in the base class. # Construct the type of the overriding method. typ = self.method_type(defn) # 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 isinstance(original_type, FunctionLike): original = map_type_from_supertype( method_type(original_type), defn.info, base ) # Check that the types are compatible. # TODO overloaded signatures self.check_override( typ, cast(FunctionLike, original), defn.name(), name, base.name(), defn ) else: assert original_type is not None self.msg.signature_incompatible_with_supertype( defn.name(), name, base.name(), defn )
https://github.com/python/mypy/issues/1972
Traceback (most recent call last): File ".../bin/mypy", line 6, in <module> main(__file__) File ".../mypy/main.py", line 40, in main res = type_check_only(sources, bin_dir, options) File ".../mypy/main.py", line 81, in type_check_only options=options) File ".../mypy/build.py", line 177, in build dispatch(sources, manager) File ".../mypy/build.py", line 1323, in dispatch process_graph(graph, manager) File ".../mypy/build.py", line 1461, in process_graph process_stale_scc(graph, scc) File ".../mypy/build.py", line 1538, in process_stale_scc graph[id].type_check() File ".../mypy/build.py", line 1301, in type_check manager.type_checker.visit_file(self.tree, self.xpath) File ".../mypy/checker.py", line 152, in visit_file self.accept(d) File ".../mypy/checker.py", line 201, in accept typ = node.accept(self) File ".../mypy/nodes.py", line 660, in accept return visitor.visit_class_def(self) File ".../mypy/checker.py", line 802, in visit_class_def self.accept(defn.defs) File ".../mypy/checker.py", line 201, in accept typ = node.accept(self) File ".../mypy/nodes.py", line 723, in accept return visitor.visit_block(self) File ".../mypy/checker.py", line 897, in visit_block self.accept(s) File ".../mypy/checker.py", line 201, in accept typ = node.accept(self) File ".../mypy/nodes.py", line 475, in accept return visitor.visit_func_def(self) File ".../mypy/checker.py", line 325, in visit_func_def self.check_method_override(defn) File ".../mypy/checker.py", line 681, in check_method_override self.check_method_or_accessor_override_for_base(defn, base) File ".../mypy/checker.py", line 690, in check_method_or_accessor_override_for_base self.check_method_override_for_base_with_name(defn, name, base) File ".../mypy/checker.py", line 728, in check_method_override_for_base_with_name assert original_type is not None AssertionError: *** INTERNAL ERROR *** /home/machinalis/0/foo/derived.py:4: error: Internal error -- please report a bug at https://github.com/python/mypy/issues
AssertionError
def lookup(self, name: str, ctx: Context) -> SymbolTableNode: """Look up an unqualified name in all active namespaces.""" # 1a. Name declared using 'global x' takes precedence if name in self.global_decls[-1]: if name in self.globals: return self.globals[name] else: self.name_not_defined(name, ctx) return None # 1b. Name declared using 'nonlocal x' takes precedence if name in self.nonlocal_decls[-1]: for table in reversed(self.locals[:-1]): if table is not None and name in table: return table[name] else: self.name_not_defined(name, ctx) return None # 2. Class attributes (if within class definition) if self.is_class_scope() and name in self.type.names: return self.type.names[name] # 3. Local (function) scopes for table in reversed(self.locals): if table is not None and name in table: return table[name] # 4. Current file global scope if name in self.globals: return self.globals[name] # 5. Builtins b = self.globals.get("__builtins__", None) if b: table = cast(MypyFile, b.node).names if name in table: if name[0] == "_" and name[1] != "_": self.name_not_defined(name, ctx) return None node = table[name] return node # Give up. self.name_not_defined(name, ctx) self.check_for_obsolete_short_name(name, ctx) return None
def lookup(self, name: str, ctx: Context) -> SymbolTableNode: """Look up an unqualified name in all active namespaces.""" # 1a. Name declared using 'global x' takes precedence if name in self.global_decls[-1]: if name in self.globals: return self.globals[name] else: self.name_not_defined(name, ctx) return None # 1b. Name declared using 'nonlocal x' takes precedence if name in self.nonlocal_decls[-1]: for table in reversed(self.locals[:-1]): if table is not None and name in table: return table[name] else: self.name_not_defined(name, ctx) return None # 2. Class attributes (if within class definition) if self.is_class_scope() and name in self.type.names: return self.type[name] # 3. Local (function) scopes for table in reversed(self.locals): if table is not None and name in table: return table[name] # 4. Current file global scope if name in self.globals: return self.globals[name] # 5. Builtins b = self.globals.get("__builtins__", None) if b: table = cast(MypyFile, b.node).names if name in table: if name[0] == "_" and name[1] != "_": self.name_not_defined(name, ctx) return None node = table[name] return node # Give up. self.name_not_defined(name, ctx) self.check_for_obsolete_short_name(name, ctx) return None
https://github.com/python/mypy/issues/2001
Traceback (most recent call last): File "/home/machinalis/.virtualenvs/mypy-django/bin/mypy", line 6, in <module> exec(compile(open(__file__).read(), __file__, 'exec')) File "/home/machinalis/oss/mypy/scripts/mypy", line 6, in <module> main(__file__) File "/home/machinalis/oss/mypy/mypy/main.py", line 38, in main res = type_check_only(sources, bin_dir, options) File "/home/machinalis/oss/mypy/mypy/main.py", line 79, in type_check_only options=options) File "/home/machinalis/oss/mypy/mypy/build.py", line 180, in build dispatch(sources, manager) File "/home/machinalis/oss/mypy/mypy/build.py", line 1335, in dispatch process_graph(graph, manager) File "/home/machinalis/oss/mypy/mypy/build.py", line 1478, in process_graph process_stale_scc(graph, scc) File "/home/machinalis/oss/mypy/mypy/build.py", line 1551, in process_stale_scc graph[id].semantic_analysis() File "/home/machinalis/oss/mypy/mypy/build.py", line 1300, in semantic_analysis self.manager.semantic_analyzer.visit_file(self.tree, self.xpath) File "/home/machinalis/oss/mypy/mypy/semanal.py", line 244, in visit_file self.accept(d) File "/home/machinalis/oss/mypy/mypy/semanal.py", line 2462, in accept node.accept(self) File "/home/machinalis/oss/mypy/mypy/nodes.py", line 664, in accept return visitor.visit_class_def(self) File "/home/machinalis/oss/mypy/mypy/semanal.py", line 572, in visit_class_def defn.defs.accept(self) File "/home/machinalis/oss/mypy/mypy/nodes.py", line 727, in accept return visitor.visit_block(self) File "/home/machinalis/oss/mypy/mypy/semanal.py", line 1028, in visit_block self.accept(s) File "/home/machinalis/oss/mypy/mypy/semanal.py", line 2462, in accept node.accept(self) File "/home/machinalis/oss/mypy/mypy/nodes.py", line 765, in accept return visitor.visit_assignment_stmt(self) File "/home/machinalis/oss/mypy/mypy/semanal.py", line 1060, in visit_assignment_stmt s.rvalue.accept(self) File "/home/machinalis/oss/mypy/mypy/nodes.py", line 1116, in accept return visitor.visit_name_expr(self) File "/home/machinalis/oss/mypy/mypy/semanal.py", line 1906, in visit_name_expr n = self.lookup(expr.name, expr) File "/home/machinalis/oss/mypy/mypy/semanal.py", line 2250, in lookup return self.type[name] File "/home/machinalis/oss/mypy/mypy/nodes.py", line 1864, in __getitem__ raise KeyError(name) KeyError: 'readlines' *** INTERNAL ERROR *** myiter.py:7: error: Internal error -- please report a bug at https://github.com/python/mypy/issues NOTE: you can use "mypy --pdb ..." to drop into the debugger when this happens.
KeyError
def leave_partial_types(self) -> None: """Pop partial type scope. Also report errors for variables which still have partial types, i.e. we couldn't infer a complete type. """ partial_types = self.partial_types.pop() if not self.current_node_deferred: for var, context in partial_types.items(): 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: self.msg.fail(messages.NEED_ANNOTATION_FOR_VAR, context) var.type = AnyType()
def leave_partial_types(self) -> None: """Pop partial type scope. Also report errors for variables which still have partial types, i.e. we couldn't infer a complete type. """ 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: # None partial type: assume variable is intended to have type None var.type = NoneTyp() else: self.msg.fail(messages.NEED_ANNOTATION_FOR_VAR, context) var.type = AnyType()
https://github.com/python/mypy/issues/1948
Traceback (most recent call last): File "/usr/lib/python-exec/python3.4/mypy", line 6, in <module> main(__file__) File "/usr/lib64/python3.4/site-packages/mypy/main.py", line 40, in main res = type_check_only(sources, bin_dir, options) File "/usr/lib64/python3.4/site-packages/mypy/main.py", line 81, in type_check_only options=options) File "/usr/lib64/python3.4/site-packages/mypy/build.py", line 178, in build dispatch(sources, manager) File "/usr/lib64/python3.4/site-packages/mypy/build.py", line 1325, in dispatch process_graph(graph, manager) File "/usr/lib64/python3.4/site-packages/mypy/build.py", line 1468, in process_graph process_stale_scc(graph, scc) File "/usr/lib64/python3.4/site-packages/mypy/build.py", line 1545, in process_stale_scc graph[id].type_check() File "/usr/lib64/python3.4/site-packages/mypy/build.py", line 1303, in type_check manager.type_checker.visit_file(self.tree, self.xpath) File "/usr/lib64/python3.4/site-packages/mypy/checker.py", line 152, in visit_file self.accept(d) File "/usr/lib64/python3.4/site-packages/mypy/checker.py", line 201, in accept typ = node.accept(self) File "/usr/lib64/python3.4/site-packages/mypy/nodes.py", line 476, in accept return visitor.visit_func_def(self) File "/usr/lib64/python3.4/site-packages/mypy/checker.py", line 399, in visit_func_def self.check_func_item(defn, name=defn.name()) File "/usr/lib64/python3.4/site-packages/mypy/checker.py", line 466, in check_func_item self.leave_partial_types() File "/usr/lib64/python3.4/site-packages/mypy/checker.py", line 2191, in leave_partial_types if experiments.STRICT_OPTIONAL and cast(PartialType, var.type).type is None: AttributeError: 'AnyType' object has no attribute 'type' *** INTERNAL ERROR *** /tmp/asd8.py:3: error: Internal error -- please report a bug at https://github.com/python/mypy/issues NOTE: you can use "mypy --pdb ..." to drop into the debugger when this happens.
AttributeError
def try_infer_partial_type(self, e: CallExpr) -> None: if isinstance(e.callee, MemberExpr) and isinstance(e.callee.expr, RefExpr): 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 = 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() methodname = e.callee.name # Sometimes we can infer a full type for a partial List, Dict or Set type. # TODO: Don't infer argument expression twice. if ( typename in self.item_args and methodname in self.item_args[typename] and e.arg_kinds == [ARG_POS] ): item_type = self.accept(e.args[0]) full_item_type = UnionType.make_simplified_union( [item_type, partial_type.inner_types[0]] ) if mypy.checker.is_valid_inferred_type(full_item_type): var.type = self.chk.named_generic_type(typename, [full_item_type]) del partial_types[var] elif ( typename in self.container_args and methodname in self.container_args[typename] and e.arg_kinds == [ARG_POS] ): arg_type = self.accept(e.args[0]) if isinstance(arg_type, Instance): arg_typename = arg_type.type.fullname() if arg_typename in self.container_args[typename][methodname]: full_item_types = [ UnionType.make_simplified_union([item_type, prev_type]) for item_type, prev_type in zip( arg_type.args, partial_type.inner_types ) ] if all( mypy.checker.is_valid_inferred_type(item_type) for item_type in full_item_types ): var.type = self.chk.named_generic_type( typename, list(full_item_types) ) del partial_types[var]
def try_infer_partial_type(self, e: CallExpr) -> None: if isinstance(e.callee, MemberExpr) and isinstance(e.callee.expr, RefExpr): 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: # A partial None type -> can't infer anything. return typename = partial_type.type.fullname() methodname = e.callee.name # Sometimes we can infer a full type for a partial List, Dict or Set type. # TODO: Don't infer argument expression twice. if ( typename in self.item_args and methodname in self.item_args[typename] and e.arg_kinds == [ARG_POS] ): item_type = self.accept(e.args[0]) full_item_type = UnionType.make_simplified_union( [item_type, partial_type.inner_types[0]] ) if mypy.checker.is_valid_inferred_type(full_item_type): var.type = self.chk.named_generic_type(typename, [full_item_type]) del partial_types[var] elif ( typename in self.container_args and methodname in self.container_args[typename] and e.arg_kinds == [ARG_POS] ): arg_type = self.accept(e.args[0]) if isinstance(arg_type, Instance): arg_typename = arg_type.type.fullname() if arg_typename in self.container_args[typename][methodname]: full_item_types = [ UnionType.make_simplified_union([item_type, prev_type]) for item_type, prev_type in zip( arg_type.args, partial_type.inner_types ) ] if all( mypy.checker.is_valid_inferred_type(item_type) for item_type in full_item_types ): var.type = self.chk.named_generic_type( typename, list(full_item_types) ) del partial_types[var]
https://github.com/python/mypy/issues/1948
Traceback (most recent call last): File "/usr/lib/python-exec/python3.4/mypy", line 6, in <module> main(__file__) File "/usr/lib64/python3.4/site-packages/mypy/main.py", line 40, in main res = type_check_only(sources, bin_dir, options) File "/usr/lib64/python3.4/site-packages/mypy/main.py", line 81, in type_check_only options=options) File "/usr/lib64/python3.4/site-packages/mypy/build.py", line 178, in build dispatch(sources, manager) File "/usr/lib64/python3.4/site-packages/mypy/build.py", line 1325, in dispatch process_graph(graph, manager) File "/usr/lib64/python3.4/site-packages/mypy/build.py", line 1468, in process_graph process_stale_scc(graph, scc) File "/usr/lib64/python3.4/site-packages/mypy/build.py", line 1545, in process_stale_scc graph[id].type_check() File "/usr/lib64/python3.4/site-packages/mypy/build.py", line 1303, in type_check manager.type_checker.visit_file(self.tree, self.xpath) File "/usr/lib64/python3.4/site-packages/mypy/checker.py", line 152, in visit_file self.accept(d) File "/usr/lib64/python3.4/site-packages/mypy/checker.py", line 201, in accept typ = node.accept(self) File "/usr/lib64/python3.4/site-packages/mypy/nodes.py", line 476, in accept return visitor.visit_func_def(self) File "/usr/lib64/python3.4/site-packages/mypy/checker.py", line 399, in visit_func_def self.check_func_item(defn, name=defn.name()) File "/usr/lib64/python3.4/site-packages/mypy/checker.py", line 466, in check_func_item self.leave_partial_types() File "/usr/lib64/python3.4/site-packages/mypy/checker.py", line 2191, in leave_partial_types if experiments.STRICT_OPTIONAL and cast(PartialType, var.type).type is None: AttributeError: 'AnyType' object has no attribute 'type' *** INTERNAL ERROR *** /tmp/asd8.py:3: error: Internal error -- please report a bug at https://github.com/python/mypy/issues NOTE: you can use "mypy --pdb ..." to drop into the debugger when this happens.
AttributeError
def visit_list_expr(self, e: ListExpr) -> Type: """Type check a list expression [...].""" return self.check_lst_expr(e.items, "builtins.list", "<list>", e)
def visit_list_expr(self, e: ListExpr) -> Type: """Type check a list expression [...].""" return self.check_list_or_set_expr(e.items, "builtins.list", "<list>", e)
https://github.com/python/mypy/issues/1722
Traceback (most recent call last): File "/home/dominik/.virtualenvs/mypy/bin/mypy", line 6, in <module> main(__file__) File "/home/dominik/.virtualenvs/mypy/lib/python3.5/site-packages/mypy/main.py", line 54, in main res = type_check_only(sources, bin_dir, options) File "/home/dominik/.virtualenvs/mypy/lib/python3.5/site-packages/mypy/main.py", line 102, in type_check_only python_path=options.python_path) File "/home/dominik/.virtualenvs/mypy/lib/python3.5/site-packages/mypy/build.py", line 211, in build dispatch(sources, manager) File "/home/dominik/.virtualenvs/mypy/lib/python3.5/site-packages/mypy/build.py", line 1336, in dispatch process_graph(graph, manager) File "/home/dominik/.virtualenvs/mypy/lib/python3.5/site-packages/mypy/build.py", line 1467, in process_graph process_stale_scc(graph, scc) File "/home/dominik/.virtualenvs/mypy/lib/python3.5/site-packages/mypy/build.py", line 1497, in process_stale_scc graph[id].type_check() File "/home/dominik/.virtualenvs/mypy/lib/python3.5/site-packages/mypy/build.py", line 1316, in type_check manager.type_checker.visit_file(self.tree, self.xpath) File "/home/dominik/.virtualenvs/mypy/lib/python3.5/site-packages/mypy/checker.py", line 426, in visit_file self.accept(d) File "/home/dominik/.virtualenvs/mypy/lib/python3.5/site-packages/mypy/checker.py", line 476, in accept typ = node.accept(self) File "/home/dominik/.virtualenvs/mypy/lib/python3.5/site-packages/mypy/nodes.py", line 729, in accept return visitor.visit_expression_stmt(self) File "/home/dominik/.virtualenvs/mypy/lib/python3.5/site-packages/mypy/checker.py", line 1582, in visit_expression_stmt self.accept(s.expr) File "/home/dominik/.virtualenvs/mypy/lib/python3.5/site-packages/mypy/checker.py", line 476, in accept typ = node.accept(self) File "/home/dominik/.virtualenvs/mypy/lib/python3.5/site-packages/mypy/nodes.py", line 1434, in accept return visitor.visit_list_expr(self) File "/home/dominik/.virtualenvs/mypy/lib/python3.5/site-packages/mypy/checker.py", line 2122, in visit_list_expr return self.expr_checker.visit_list_expr(e) File "/home/dominik/.virtualenvs/mypy/lib/python3.5/site-packages/mypy/checkexpr.py", line 1251, in visit_list_expr e) File "/home/dominik/.virtualenvs/mypy/lib/python3.5/site-packages/mypy/checkexpr.py", line 1270, in check_list_or_set_expr [nodes.ARG_POS] * len(items), context)[0] File "/home/dominik/.virtualenvs/mypy/lib/python3.5/site-packages/mypy/checkexpr.py", line 242, in check_call messages=arg_messages) File "/home/dominik/.virtualenvs/mypy/lib/python3.5/site-packages/mypy/checkexpr.py", line 661, in check_argument_types actual + 1, i + 1, callee, context, messages) File "/home/dominik/.virtualenvs/mypy/lib/python3.5/site-packages/mypy/checkexpr.py", line 686, in check_arg elif not is_subtype(caller_type, callee_type): File "/home/dominik/.virtualenvs/mypy/lib/python3.5/site-packages/mypy/subtypes.py", line 49, in is_subtype return left.accept(SubtypeVisitor(right, type_parameter_checker)) AttributeError: 'NoneType' object has no attribute 'accept'
AttributeError
def visit_set_expr(self, e: SetExpr) -> Type: return self.check_lst_expr(e.items, "builtins.set", "<set>", e)
def visit_set_expr(self, e: SetExpr) -> Type: return self.check_list_or_set_expr(e.items, "builtins.set", "<set>", e)
https://github.com/python/mypy/issues/1722
Traceback (most recent call last): File "/home/dominik/.virtualenvs/mypy/bin/mypy", line 6, in <module> main(__file__) File "/home/dominik/.virtualenvs/mypy/lib/python3.5/site-packages/mypy/main.py", line 54, in main res = type_check_only(sources, bin_dir, options) File "/home/dominik/.virtualenvs/mypy/lib/python3.5/site-packages/mypy/main.py", line 102, in type_check_only python_path=options.python_path) File "/home/dominik/.virtualenvs/mypy/lib/python3.5/site-packages/mypy/build.py", line 211, in build dispatch(sources, manager) File "/home/dominik/.virtualenvs/mypy/lib/python3.5/site-packages/mypy/build.py", line 1336, in dispatch process_graph(graph, manager) File "/home/dominik/.virtualenvs/mypy/lib/python3.5/site-packages/mypy/build.py", line 1467, in process_graph process_stale_scc(graph, scc) File "/home/dominik/.virtualenvs/mypy/lib/python3.5/site-packages/mypy/build.py", line 1497, in process_stale_scc graph[id].type_check() File "/home/dominik/.virtualenvs/mypy/lib/python3.5/site-packages/mypy/build.py", line 1316, in type_check manager.type_checker.visit_file(self.tree, self.xpath) File "/home/dominik/.virtualenvs/mypy/lib/python3.5/site-packages/mypy/checker.py", line 426, in visit_file self.accept(d) File "/home/dominik/.virtualenvs/mypy/lib/python3.5/site-packages/mypy/checker.py", line 476, in accept typ = node.accept(self) File "/home/dominik/.virtualenvs/mypy/lib/python3.5/site-packages/mypy/nodes.py", line 729, in accept return visitor.visit_expression_stmt(self) File "/home/dominik/.virtualenvs/mypy/lib/python3.5/site-packages/mypy/checker.py", line 1582, in visit_expression_stmt self.accept(s.expr) File "/home/dominik/.virtualenvs/mypy/lib/python3.5/site-packages/mypy/checker.py", line 476, in accept typ = node.accept(self) File "/home/dominik/.virtualenvs/mypy/lib/python3.5/site-packages/mypy/nodes.py", line 1434, in accept return visitor.visit_list_expr(self) File "/home/dominik/.virtualenvs/mypy/lib/python3.5/site-packages/mypy/checker.py", line 2122, in visit_list_expr return self.expr_checker.visit_list_expr(e) File "/home/dominik/.virtualenvs/mypy/lib/python3.5/site-packages/mypy/checkexpr.py", line 1251, in visit_list_expr e) File "/home/dominik/.virtualenvs/mypy/lib/python3.5/site-packages/mypy/checkexpr.py", line 1270, in check_list_or_set_expr [nodes.ARG_POS] * len(items), context)[0] File "/home/dominik/.virtualenvs/mypy/lib/python3.5/site-packages/mypy/checkexpr.py", line 242, in check_call messages=arg_messages) File "/home/dominik/.virtualenvs/mypy/lib/python3.5/site-packages/mypy/checkexpr.py", line 661, in check_argument_types actual + 1, i + 1, callee, context, messages) File "/home/dominik/.virtualenvs/mypy/lib/python3.5/site-packages/mypy/checkexpr.py", line 686, in check_arg elif not is_subtype(caller_type, callee_type): File "/home/dominik/.virtualenvs/mypy/lib/python3.5/site-packages/mypy/subtypes.py", line 49, in is_subtype return left.accept(SubtypeVisitor(right, type_parameter_checker)) AttributeError: 'NoneType' object has no attribute 'accept'
AttributeError
def visit_tuple_expr(self, e: TupleExpr) -> Type: """Type check a tuple expression.""" ctx = None # type: TupleType # Try to determine type context for type inference. if isinstance(self.chk.type_context[-1], TupleType): t = self.chk.type_context[-1] ctx = t # NOTE: it's possible for the context to have a different # number of items than e. In that case we use those context # items that match a position in e, and we'll worry about type # mismatches later. # Infer item types. Give up if there's a star expression # that's not a Tuple. items = [] # type: List[Type] j = 0 # Index into ctx.items; irrelevant if ctx is None. for i in range(len(e.items)): item = e.items[i] tt = None # type: Type if isinstance(item, StarExpr): # Special handling for star expressions. # TODO: If there's a context, and item.expr is a # TupleExpr, flatten it, so we can benefit from the # context? Counterargument: Why would anyone write # (1, *(2, 3)) instead of (1, 2, 3) except in a test? tt = self.accept(item.expr) self.check_not_void(tt, e) if isinstance(tt, TupleType): items.extend(tt.items) j += len(tt.items) else: # A star expression that's not a Tuple. # Treat the whole thing as a variable-length tuple. return self.check_lst_expr(e.items, "builtins.tuple", "<tuple>", e) else: if not ctx or j >= len(ctx.items): tt = self.accept(item) else: tt = self.accept(item, ctx.items[j]) j += 1 self.check_not_void(tt, e) items.append(tt) fallback_item = join.join_type_list(items) return TupleType( items, self.chk.named_generic_type("builtins.tuple", [fallback_item]) )
def visit_tuple_expr(self, e: TupleExpr) -> Type: """Type check a tuple expression.""" ctx = None # type: TupleType # Try to determine type context for type inference. if isinstance(self.chk.type_context[-1], TupleType): t = self.chk.type_context[-1] if len(t.items) == len(e.items): ctx = t # Infer item types. items = [] # type: List[Type] for i in range(len(e.items)): item = e.items[i] tt = None # type: Type if not ctx: tt = self.accept(item) else: tt = self.accept(item, ctx.items[i]) self.check_not_void(tt, e) items.append(tt) fallback_item = join.join_type_list(items) return TupleType( items, self.chk.named_generic_type("builtins.tuple", [fallback_item]) )
https://github.com/python/mypy/issues/1722
Traceback (most recent call last): File "/home/dominik/.virtualenvs/mypy/bin/mypy", line 6, in <module> main(__file__) File "/home/dominik/.virtualenvs/mypy/lib/python3.5/site-packages/mypy/main.py", line 54, in main res = type_check_only(sources, bin_dir, options) File "/home/dominik/.virtualenvs/mypy/lib/python3.5/site-packages/mypy/main.py", line 102, in type_check_only python_path=options.python_path) File "/home/dominik/.virtualenvs/mypy/lib/python3.5/site-packages/mypy/build.py", line 211, in build dispatch(sources, manager) File "/home/dominik/.virtualenvs/mypy/lib/python3.5/site-packages/mypy/build.py", line 1336, in dispatch process_graph(graph, manager) File "/home/dominik/.virtualenvs/mypy/lib/python3.5/site-packages/mypy/build.py", line 1467, in process_graph process_stale_scc(graph, scc) File "/home/dominik/.virtualenvs/mypy/lib/python3.5/site-packages/mypy/build.py", line 1497, in process_stale_scc graph[id].type_check() File "/home/dominik/.virtualenvs/mypy/lib/python3.5/site-packages/mypy/build.py", line 1316, in type_check manager.type_checker.visit_file(self.tree, self.xpath) File "/home/dominik/.virtualenvs/mypy/lib/python3.5/site-packages/mypy/checker.py", line 426, in visit_file self.accept(d) File "/home/dominik/.virtualenvs/mypy/lib/python3.5/site-packages/mypy/checker.py", line 476, in accept typ = node.accept(self) File "/home/dominik/.virtualenvs/mypy/lib/python3.5/site-packages/mypy/nodes.py", line 729, in accept return visitor.visit_expression_stmt(self) File "/home/dominik/.virtualenvs/mypy/lib/python3.5/site-packages/mypy/checker.py", line 1582, in visit_expression_stmt self.accept(s.expr) File "/home/dominik/.virtualenvs/mypy/lib/python3.5/site-packages/mypy/checker.py", line 476, in accept typ = node.accept(self) File "/home/dominik/.virtualenvs/mypy/lib/python3.5/site-packages/mypy/nodes.py", line 1434, in accept return visitor.visit_list_expr(self) File "/home/dominik/.virtualenvs/mypy/lib/python3.5/site-packages/mypy/checker.py", line 2122, in visit_list_expr return self.expr_checker.visit_list_expr(e) File "/home/dominik/.virtualenvs/mypy/lib/python3.5/site-packages/mypy/checkexpr.py", line 1251, in visit_list_expr e) File "/home/dominik/.virtualenvs/mypy/lib/python3.5/site-packages/mypy/checkexpr.py", line 1270, in check_list_or_set_expr [nodes.ARG_POS] * len(items), context)[0] File "/home/dominik/.virtualenvs/mypy/lib/python3.5/site-packages/mypy/checkexpr.py", line 242, in check_call messages=arg_messages) File "/home/dominik/.virtualenvs/mypy/lib/python3.5/site-packages/mypy/checkexpr.py", line 661, in check_argument_types actual + 1, i + 1, callee, context, messages) File "/home/dominik/.virtualenvs/mypy/lib/python3.5/site-packages/mypy/checkexpr.py", line 686, in check_arg elif not is_subtype(caller_type, callee_type): File "/home/dominik/.virtualenvs/mypy/lib/python3.5/site-packages/mypy/subtypes.py", line 49, in is_subtype return left.accept(SubtypeVisitor(right, type_parameter_checker)) AttributeError: 'NoneType' object has no attribute 'accept'
AttributeError
def visit_tuple_expr(self, expr: TupleExpr) -> None: for item in expr.items: if isinstance(item, StarExpr): item.valid = True item.accept(self)
def visit_tuple_expr(self, expr: TupleExpr) -> None: for item in expr.items: item.accept(self)
https://github.com/python/mypy/issues/1722
Traceback (most recent call last): File "/home/dominik/.virtualenvs/mypy/bin/mypy", line 6, in <module> main(__file__) File "/home/dominik/.virtualenvs/mypy/lib/python3.5/site-packages/mypy/main.py", line 54, in main res = type_check_only(sources, bin_dir, options) File "/home/dominik/.virtualenvs/mypy/lib/python3.5/site-packages/mypy/main.py", line 102, in type_check_only python_path=options.python_path) File "/home/dominik/.virtualenvs/mypy/lib/python3.5/site-packages/mypy/build.py", line 211, in build dispatch(sources, manager) File "/home/dominik/.virtualenvs/mypy/lib/python3.5/site-packages/mypy/build.py", line 1336, in dispatch process_graph(graph, manager) File "/home/dominik/.virtualenvs/mypy/lib/python3.5/site-packages/mypy/build.py", line 1467, in process_graph process_stale_scc(graph, scc) File "/home/dominik/.virtualenvs/mypy/lib/python3.5/site-packages/mypy/build.py", line 1497, in process_stale_scc graph[id].type_check() File "/home/dominik/.virtualenvs/mypy/lib/python3.5/site-packages/mypy/build.py", line 1316, in type_check manager.type_checker.visit_file(self.tree, self.xpath) File "/home/dominik/.virtualenvs/mypy/lib/python3.5/site-packages/mypy/checker.py", line 426, in visit_file self.accept(d) File "/home/dominik/.virtualenvs/mypy/lib/python3.5/site-packages/mypy/checker.py", line 476, in accept typ = node.accept(self) File "/home/dominik/.virtualenvs/mypy/lib/python3.5/site-packages/mypy/nodes.py", line 729, in accept return visitor.visit_expression_stmt(self) File "/home/dominik/.virtualenvs/mypy/lib/python3.5/site-packages/mypy/checker.py", line 1582, in visit_expression_stmt self.accept(s.expr) File "/home/dominik/.virtualenvs/mypy/lib/python3.5/site-packages/mypy/checker.py", line 476, in accept typ = node.accept(self) File "/home/dominik/.virtualenvs/mypy/lib/python3.5/site-packages/mypy/nodes.py", line 1434, in accept return visitor.visit_list_expr(self) File "/home/dominik/.virtualenvs/mypy/lib/python3.5/site-packages/mypy/checker.py", line 2122, in visit_list_expr return self.expr_checker.visit_list_expr(e) File "/home/dominik/.virtualenvs/mypy/lib/python3.5/site-packages/mypy/checkexpr.py", line 1251, in visit_list_expr e) File "/home/dominik/.virtualenvs/mypy/lib/python3.5/site-packages/mypy/checkexpr.py", line 1270, in check_list_or_set_expr [nodes.ARG_POS] * len(items), context)[0] File "/home/dominik/.virtualenvs/mypy/lib/python3.5/site-packages/mypy/checkexpr.py", line 242, in check_call messages=arg_messages) File "/home/dominik/.virtualenvs/mypy/lib/python3.5/site-packages/mypy/checkexpr.py", line 661, in check_argument_types actual + 1, i + 1, callee, context, messages) File "/home/dominik/.virtualenvs/mypy/lib/python3.5/site-packages/mypy/checkexpr.py", line 686, in check_arg elif not is_subtype(caller_type, callee_type): File "/home/dominik/.virtualenvs/mypy/lib/python3.5/site-packages/mypy/subtypes.py", line 49, in is_subtype return left.accept(SubtypeVisitor(right, type_parameter_checker)) AttributeError: 'NoneType' object has no attribute 'accept'
AttributeError
def visit_list_expr(self, expr: ListExpr) -> None: for item in expr.items: if isinstance(item, StarExpr): item.valid = True item.accept(self)
def visit_list_expr(self, expr: ListExpr) -> None: for item in expr.items: item.accept(self)
https://github.com/python/mypy/issues/1722
Traceback (most recent call last): File "/home/dominik/.virtualenvs/mypy/bin/mypy", line 6, in <module> main(__file__) File "/home/dominik/.virtualenvs/mypy/lib/python3.5/site-packages/mypy/main.py", line 54, in main res = type_check_only(sources, bin_dir, options) File "/home/dominik/.virtualenvs/mypy/lib/python3.5/site-packages/mypy/main.py", line 102, in type_check_only python_path=options.python_path) File "/home/dominik/.virtualenvs/mypy/lib/python3.5/site-packages/mypy/build.py", line 211, in build dispatch(sources, manager) File "/home/dominik/.virtualenvs/mypy/lib/python3.5/site-packages/mypy/build.py", line 1336, in dispatch process_graph(graph, manager) File "/home/dominik/.virtualenvs/mypy/lib/python3.5/site-packages/mypy/build.py", line 1467, in process_graph process_stale_scc(graph, scc) File "/home/dominik/.virtualenvs/mypy/lib/python3.5/site-packages/mypy/build.py", line 1497, in process_stale_scc graph[id].type_check() File "/home/dominik/.virtualenvs/mypy/lib/python3.5/site-packages/mypy/build.py", line 1316, in type_check manager.type_checker.visit_file(self.tree, self.xpath) File "/home/dominik/.virtualenvs/mypy/lib/python3.5/site-packages/mypy/checker.py", line 426, in visit_file self.accept(d) File "/home/dominik/.virtualenvs/mypy/lib/python3.5/site-packages/mypy/checker.py", line 476, in accept typ = node.accept(self) File "/home/dominik/.virtualenvs/mypy/lib/python3.5/site-packages/mypy/nodes.py", line 729, in accept return visitor.visit_expression_stmt(self) File "/home/dominik/.virtualenvs/mypy/lib/python3.5/site-packages/mypy/checker.py", line 1582, in visit_expression_stmt self.accept(s.expr) File "/home/dominik/.virtualenvs/mypy/lib/python3.5/site-packages/mypy/checker.py", line 476, in accept typ = node.accept(self) File "/home/dominik/.virtualenvs/mypy/lib/python3.5/site-packages/mypy/nodes.py", line 1434, in accept return visitor.visit_list_expr(self) File "/home/dominik/.virtualenvs/mypy/lib/python3.5/site-packages/mypy/checker.py", line 2122, in visit_list_expr return self.expr_checker.visit_list_expr(e) File "/home/dominik/.virtualenvs/mypy/lib/python3.5/site-packages/mypy/checkexpr.py", line 1251, in visit_list_expr e) File "/home/dominik/.virtualenvs/mypy/lib/python3.5/site-packages/mypy/checkexpr.py", line 1270, in check_list_or_set_expr [nodes.ARG_POS] * len(items), context)[0] File "/home/dominik/.virtualenvs/mypy/lib/python3.5/site-packages/mypy/checkexpr.py", line 242, in check_call messages=arg_messages) File "/home/dominik/.virtualenvs/mypy/lib/python3.5/site-packages/mypy/checkexpr.py", line 661, in check_argument_types actual + 1, i + 1, callee, context, messages) File "/home/dominik/.virtualenvs/mypy/lib/python3.5/site-packages/mypy/checkexpr.py", line 686, in check_arg elif not is_subtype(caller_type, callee_type): File "/home/dominik/.virtualenvs/mypy/lib/python3.5/site-packages/mypy/subtypes.py", line 49, in is_subtype return left.accept(SubtypeVisitor(right, type_parameter_checker)) AttributeError: 'NoneType' object has no attribute 'accept'
AttributeError
def visit_set_expr(self, expr: SetExpr) -> None: for item in expr.items: if isinstance(item, StarExpr): item.valid = True item.accept(self)
def visit_set_expr(self, expr: SetExpr) -> None: for item in expr.items: item.accept(self)
https://github.com/python/mypy/issues/1722
Traceback (most recent call last): File "/home/dominik/.virtualenvs/mypy/bin/mypy", line 6, in <module> main(__file__) File "/home/dominik/.virtualenvs/mypy/lib/python3.5/site-packages/mypy/main.py", line 54, in main res = type_check_only(sources, bin_dir, options) File "/home/dominik/.virtualenvs/mypy/lib/python3.5/site-packages/mypy/main.py", line 102, in type_check_only python_path=options.python_path) File "/home/dominik/.virtualenvs/mypy/lib/python3.5/site-packages/mypy/build.py", line 211, in build dispatch(sources, manager) File "/home/dominik/.virtualenvs/mypy/lib/python3.5/site-packages/mypy/build.py", line 1336, in dispatch process_graph(graph, manager) File "/home/dominik/.virtualenvs/mypy/lib/python3.5/site-packages/mypy/build.py", line 1467, in process_graph process_stale_scc(graph, scc) File "/home/dominik/.virtualenvs/mypy/lib/python3.5/site-packages/mypy/build.py", line 1497, in process_stale_scc graph[id].type_check() File "/home/dominik/.virtualenvs/mypy/lib/python3.5/site-packages/mypy/build.py", line 1316, in type_check manager.type_checker.visit_file(self.tree, self.xpath) File "/home/dominik/.virtualenvs/mypy/lib/python3.5/site-packages/mypy/checker.py", line 426, in visit_file self.accept(d) File "/home/dominik/.virtualenvs/mypy/lib/python3.5/site-packages/mypy/checker.py", line 476, in accept typ = node.accept(self) File "/home/dominik/.virtualenvs/mypy/lib/python3.5/site-packages/mypy/nodes.py", line 729, in accept return visitor.visit_expression_stmt(self) File "/home/dominik/.virtualenvs/mypy/lib/python3.5/site-packages/mypy/checker.py", line 1582, in visit_expression_stmt self.accept(s.expr) File "/home/dominik/.virtualenvs/mypy/lib/python3.5/site-packages/mypy/checker.py", line 476, in accept typ = node.accept(self) File "/home/dominik/.virtualenvs/mypy/lib/python3.5/site-packages/mypy/nodes.py", line 1434, in accept return visitor.visit_list_expr(self) File "/home/dominik/.virtualenvs/mypy/lib/python3.5/site-packages/mypy/checker.py", line 2122, in visit_list_expr return self.expr_checker.visit_list_expr(e) File "/home/dominik/.virtualenvs/mypy/lib/python3.5/site-packages/mypy/checkexpr.py", line 1251, in visit_list_expr e) File "/home/dominik/.virtualenvs/mypy/lib/python3.5/site-packages/mypy/checkexpr.py", line 1270, in check_list_or_set_expr [nodes.ARG_POS] * len(items), context)[0] File "/home/dominik/.virtualenvs/mypy/lib/python3.5/site-packages/mypy/checkexpr.py", line 242, in check_call messages=arg_messages) File "/home/dominik/.virtualenvs/mypy/lib/python3.5/site-packages/mypy/checkexpr.py", line 661, in check_argument_types actual + 1, i + 1, callee, context, messages) File "/home/dominik/.virtualenvs/mypy/lib/python3.5/site-packages/mypy/checkexpr.py", line 686, in check_arg elif not is_subtype(caller_type, callee_type): File "/home/dominik/.virtualenvs/mypy/lib/python3.5/site-packages/mypy/subtypes.py", line 49, in is_subtype return left.accept(SubtypeVisitor(right, type_parameter_checker)) AttributeError: 'NoneType' object has no attribute 'accept'
AttributeError
def visit_star_expr(self, expr: StarExpr) -> None: if not expr.valid: # XXX TODO Change this error message self.fail("Can use starred expression only as assignment target", expr) else: expr.expr.accept(self)
def visit_star_expr(self, expr: StarExpr) -> None: if not expr.valid: self.fail("Can use starred expression only as assignment target", expr) else: expr.expr.accept(self)
https://github.com/python/mypy/issues/1722
Traceback (most recent call last): File "/home/dominik/.virtualenvs/mypy/bin/mypy", line 6, in <module> main(__file__) File "/home/dominik/.virtualenvs/mypy/lib/python3.5/site-packages/mypy/main.py", line 54, in main res = type_check_only(sources, bin_dir, options) File "/home/dominik/.virtualenvs/mypy/lib/python3.5/site-packages/mypy/main.py", line 102, in type_check_only python_path=options.python_path) File "/home/dominik/.virtualenvs/mypy/lib/python3.5/site-packages/mypy/build.py", line 211, in build dispatch(sources, manager) File "/home/dominik/.virtualenvs/mypy/lib/python3.5/site-packages/mypy/build.py", line 1336, in dispatch process_graph(graph, manager) File "/home/dominik/.virtualenvs/mypy/lib/python3.5/site-packages/mypy/build.py", line 1467, in process_graph process_stale_scc(graph, scc) File "/home/dominik/.virtualenvs/mypy/lib/python3.5/site-packages/mypy/build.py", line 1497, in process_stale_scc graph[id].type_check() File "/home/dominik/.virtualenvs/mypy/lib/python3.5/site-packages/mypy/build.py", line 1316, in type_check manager.type_checker.visit_file(self.tree, self.xpath) File "/home/dominik/.virtualenvs/mypy/lib/python3.5/site-packages/mypy/checker.py", line 426, in visit_file self.accept(d) File "/home/dominik/.virtualenvs/mypy/lib/python3.5/site-packages/mypy/checker.py", line 476, in accept typ = node.accept(self) File "/home/dominik/.virtualenvs/mypy/lib/python3.5/site-packages/mypy/nodes.py", line 729, in accept return visitor.visit_expression_stmt(self) File "/home/dominik/.virtualenvs/mypy/lib/python3.5/site-packages/mypy/checker.py", line 1582, in visit_expression_stmt self.accept(s.expr) File "/home/dominik/.virtualenvs/mypy/lib/python3.5/site-packages/mypy/checker.py", line 476, in accept typ = node.accept(self) File "/home/dominik/.virtualenvs/mypy/lib/python3.5/site-packages/mypy/nodes.py", line 1434, in accept return visitor.visit_list_expr(self) File "/home/dominik/.virtualenvs/mypy/lib/python3.5/site-packages/mypy/checker.py", line 2122, in visit_list_expr return self.expr_checker.visit_list_expr(e) File "/home/dominik/.virtualenvs/mypy/lib/python3.5/site-packages/mypy/checkexpr.py", line 1251, in visit_list_expr e) File "/home/dominik/.virtualenvs/mypy/lib/python3.5/site-packages/mypy/checkexpr.py", line 1270, in check_list_or_set_expr [nodes.ARG_POS] * len(items), context)[0] File "/home/dominik/.virtualenvs/mypy/lib/python3.5/site-packages/mypy/checkexpr.py", line 242, in check_call messages=arg_messages) File "/home/dominik/.virtualenvs/mypy/lib/python3.5/site-packages/mypy/checkexpr.py", line 661, in check_argument_types actual + 1, i + 1, callee, context, messages) File "/home/dominik/.virtualenvs/mypy/lib/python3.5/site-packages/mypy/checkexpr.py", line 686, in check_arg elif not is_subtype(caller_type, callee_type): File "/home/dominik/.virtualenvs/mypy/lib/python3.5/site-packages/mypy/subtypes.py", line 49, in is_subtype return left.accept(SubtypeVisitor(right, type_parameter_checker)) AttributeError: 'NoneType' object has no attribute 'accept'
AttributeError
def analyze_base_classes(self, defn: ClassDef) -> None: """Analyze and set up base classes. This computes several attributes on the corresponding TypeInfo defn.info related to the base classes: defn.info.bases, defn.info.mro, and miscellaneous others (at least tuple_type, fallback_to_any, and is_enum.) """ base_types = [] # type: List[Instance] for base_expr in defn.base_type_exprs: try: base = self.expr_to_analyzed_type(base_expr) except TypeTranslationError: self.fail("Invalid base class", base_expr) defn.info.fallback_to_any = True continue if isinstance(base, TupleType): if defn.info.tuple_type: self.fail("Class has two incompatible bases derived from tuple", defn) if ( not self.is_stub_file and not defn.info.is_named_tuple and base.fallback.type.fullname() == "builtins.tuple" ): self.fail( "Tuple[...] not supported as a base class outside a stub file", defn ) defn.info.tuple_type = base base_types.append(base.fallback) elif isinstance(base, Instance): base_types.append(base) elif isinstance(base, AnyType): defn.info.fallback_to_any = True else: self.fail("Invalid base class", base_expr) defn.info.fallback_to_any = True # Add 'object' as implicit base if there is no other base class. if not base_types and defn.fullname != "builtins.object": base_types.append(self.object_type()) defn.info.bases = base_types # Calculate the MRO. It might be incomplete at this point if # the bases of defn include classes imported from other # modules in an import loop. We'll recompute it in ThirdPass. if not self.verify_base_classes(defn): # Give it an MRO consisting of just the class itself and object. defn.info.mro = [defn.info, self.object_type().type] return calculate_class_mro(defn, self.fail_blocker) # If there are cyclic imports, we may be missing 'object' in # the MRO. Fix MRO if needed. if defn.info.mro and defn.info.mro[-1].fullname() != "builtins.object": defn.info.mro.append(self.object_type().type)
def analyze_base_classes(self, defn: ClassDef) -> None: """Analyze and set up base classes. This computes several attributes on the corresponding TypeInfo defn.info related to the base classes: defn.info.bases, defn.info.mro, and miscellaneous others (at least tuple_type, fallback_to_any, and is_enum.) """ base_types = [] # type: List[Instance] for base_expr in defn.base_type_exprs: try: base = self.expr_to_analyzed_type(base_expr) except TypeTranslationError: self.fail("Invalid base class", base_expr) defn.info.fallback_to_any = True continue if isinstance(base, TupleType): if defn.info.tuple_type: self.fail("Class has two incompatible bases derived from tuple", defn) if ( not self.is_stub_file and not defn.info.is_named_tuple and base.fallback.type.fullname() == "builtins.tuple" ): self.fail( "Tuple[...] not supported as a base class outside a stub file", defn ) defn.info.tuple_type = base base_types.append(base.fallback) elif isinstance(base, Instance): base_types.append(base) elif isinstance(base, AnyType): defn.info.fallback_to_any = True else: self.fail("Invalid base class", base_expr) defn.info.fallback_to_any = True # Add 'object' as implicit base if there is no other base class. if not base_types and defn.fullname != "builtins.object": base_types.append(self.object_type()) defn.info.bases = base_types # Calculate the MRO. It might be incomplete at this point if # the bases of defn include classes imported from other # modules in an import loop. We'll recompute it in ThirdPass. if not self.verify_base_classes(defn): # Give it an MRO consisting of just the class itself and object. defn.info.mro = [defn.info, self.object_type().type] return calculate_class_mro(defn, self.fail) # If there are cyclic imports, we may be missing 'object' in # the MRO. Fix MRO if needed. if defn.info.mro and defn.info.mro[-1].fullname() != "builtins.object": defn.info.mro.append(self.object_type().type)
https://github.com/python/mypy/issues/1794
Traceback (most recent call last): File "C:\Program Files\Python35\Scripts\mypy", line 6, in <module> main(__file__) File "C:\Program Files\Python35\lib\site-packages\mypy\main.py", line 54, in main res = type_check_only(sources, bin_dir, options) File "C:\Program Files\Python35\lib\site-packages\mypy\main.py", line 102, in type_check_only python_path=options.python_path) File "C:\Program Files\Python35\lib\site-packages\mypy\build.py", line 211, in build dispatch(sources, manager) File "C:\Program Files\Python35\lib\site-packages\mypy\build.py", line 1336, in dispatch process_graph(graph, manager) File "C:\Program Files\Python35\lib\site-packages\mypy\build.py", line 1467, in process_graph process_stale_scc(graph, scc) File "C:\Program Files\Python35\lib\site-packages\mypy\build.py", line 1497, in process_stale_scc graph[id].type_check() File "C:\Program Files\Python35\lib\site-packages\mypy\build.py", line 1316, in type_check manager.type_checker.visit_file(self.tree, self.xpath) File "C:\Program Files\Python35\lib\site-packages\mypy\checker.py", line 426, in visit_file self.accept(d) File "C:\Program Files\Python35\lib\site-packages\mypy\checker.py", line 476, in accept typ = node.accept(self) File "C:\Program Files\Python35\lib\site-packages\mypy\nodes.py", line 650, in accept return visitor.visit_class_def(self) File "C:\Program Files\Python35\lib\site-packages\mypy\checker.py", line 1068, in visit_class_def self.check_multiple_inheritance(typ) File "C:\Program Files\Python35\lib\site-packages\mypy\checker.py", line 1093, in check_multiple_inheritance if not (base1 in base2.mro or base2 in base1.mro): AttributeError: 'NoneType' object has no attribute 'mro' *** INTERNAL ERROR *** mypybug.py:20: error: Internal error -- please report a bug at https://github.com/python/mypy/issues NOTE: you can use "mypy --pdb ..." to drop into the debugger when this happens.
AttributeError
def visit_class_def(self, tdef: ClassDef) -> None: for type in tdef.info.bases: self.analyze(type) # Recompute MRO now that we have analyzed all modules, to pick # up superclasses of bases imported from other modules in an # import loop. (Only do so if we succeeded the first time.) if tdef.info.mro: tdef.info.mro = [] # Force recomputation calculate_class_mro(tdef, self.fail_blocker) super().visit_class_def(tdef)
def visit_class_def(self, tdef: ClassDef) -> None: for type in tdef.info.bases: self.analyze(type) # Recompute MRO now that we have analyzed all modules, to pick # up superclasses of bases imported from other modules in an # import loop. (Only do so if we succeeded the first time.) if tdef.info.mro: tdef.info.mro = [] # Force recomputation calculate_class_mro(tdef, self.fail) super().visit_class_def(tdef)
https://github.com/python/mypy/issues/1794
Traceback (most recent call last): File "C:\Program Files\Python35\Scripts\mypy", line 6, in <module> main(__file__) File "C:\Program Files\Python35\lib\site-packages\mypy\main.py", line 54, in main res = type_check_only(sources, bin_dir, options) File "C:\Program Files\Python35\lib\site-packages\mypy\main.py", line 102, in type_check_only python_path=options.python_path) File "C:\Program Files\Python35\lib\site-packages\mypy\build.py", line 211, in build dispatch(sources, manager) File "C:\Program Files\Python35\lib\site-packages\mypy\build.py", line 1336, in dispatch process_graph(graph, manager) File "C:\Program Files\Python35\lib\site-packages\mypy\build.py", line 1467, in process_graph process_stale_scc(graph, scc) File "C:\Program Files\Python35\lib\site-packages\mypy\build.py", line 1497, in process_stale_scc graph[id].type_check() File "C:\Program Files\Python35\lib\site-packages\mypy\build.py", line 1316, in type_check manager.type_checker.visit_file(self.tree, self.xpath) File "C:\Program Files\Python35\lib\site-packages\mypy\checker.py", line 426, in visit_file self.accept(d) File "C:\Program Files\Python35\lib\site-packages\mypy\checker.py", line 476, in accept typ = node.accept(self) File "C:\Program Files\Python35\lib\site-packages\mypy\nodes.py", line 650, in accept return visitor.visit_class_def(self) File "C:\Program Files\Python35\lib\site-packages\mypy\checker.py", line 1068, in visit_class_def self.check_multiple_inheritance(typ) File "C:\Program Files\Python35\lib\site-packages\mypy\checker.py", line 1093, in check_multiple_inheritance if not (base1 in base2.mro or base2 in base1.mro): AttributeError: 'NoneType' object has no attribute 'mro' *** INTERNAL ERROR *** mypybug.py:20: error: Internal error -- please report a bug at https://github.com/python/mypy/issues NOTE: you can use "mypy --pdb ..." to drop into the debugger when this happens.
AttributeError
def fail(self, msg: str, ctx: Context, *, blocker: bool = False) -> None: self.errors.report(ctx.get_line(), msg)
def fail(self, msg: str, ctx: Context) -> None: self.errors.report(ctx.get_line(), msg)
https://github.com/python/mypy/issues/1794
Traceback (most recent call last): File "C:\Program Files\Python35\Scripts\mypy", line 6, in <module> main(__file__) File "C:\Program Files\Python35\lib\site-packages\mypy\main.py", line 54, in main res = type_check_only(sources, bin_dir, options) File "C:\Program Files\Python35\lib\site-packages\mypy\main.py", line 102, in type_check_only python_path=options.python_path) File "C:\Program Files\Python35\lib\site-packages\mypy\build.py", line 211, in build dispatch(sources, manager) File "C:\Program Files\Python35\lib\site-packages\mypy\build.py", line 1336, in dispatch process_graph(graph, manager) File "C:\Program Files\Python35\lib\site-packages\mypy\build.py", line 1467, in process_graph process_stale_scc(graph, scc) File "C:\Program Files\Python35\lib\site-packages\mypy\build.py", line 1497, in process_stale_scc graph[id].type_check() File "C:\Program Files\Python35\lib\site-packages\mypy\build.py", line 1316, in type_check manager.type_checker.visit_file(self.tree, self.xpath) File "C:\Program Files\Python35\lib\site-packages\mypy\checker.py", line 426, in visit_file self.accept(d) File "C:\Program Files\Python35\lib\site-packages\mypy\checker.py", line 476, in accept typ = node.accept(self) File "C:\Program Files\Python35\lib\site-packages\mypy\nodes.py", line 650, in accept return visitor.visit_class_def(self) File "C:\Program Files\Python35\lib\site-packages\mypy\checker.py", line 1068, in visit_class_def self.check_multiple_inheritance(typ) File "C:\Program Files\Python35\lib\site-packages\mypy\checker.py", line 1093, in check_multiple_inheritance if not (base1 in base2.mro or base2 in base1.mro): AttributeError: 'NoneType' object has no attribute 'mro' *** INTERNAL ERROR *** mypybug.py:20: error: Internal error -- please report a bug at https://github.com/python/mypy/issues NOTE: you can use "mypy --pdb ..." to drop into the debugger when this happens.
AttributeError
def check_argument_types( self, arg_types: List[Type], arg_kinds: List[int], callee: CallableType, formal_to_actual: List[List[int]], context: Context, messages: MessageBuilder = None, check_arg: ArgChecker = None, ) -> None: """Check argument types against a callable type. Report errors if the argument types are not compatible. """ messages = messages or self.msg check_arg = check_arg or self.check_arg # Keep track of consumed tuple *arg items. tuple_counter = [0] for i, actuals in enumerate(formal_to_actual): for actual in actuals: arg_type = arg_types[actual] if arg_type is None: continue # Some kind of error was already reported. # Check that a *arg is valid as varargs. if arg_kinds[actual] == nodes.ARG_STAR and not self.is_valid_var_arg( arg_type ): messages.invalid_var_arg(arg_type, context) if arg_kinds[ actual ] == nodes.ARG_STAR2 and not self.is_valid_keyword_var_arg(arg_type): messages.invalid_keyword_var_arg(arg_type, context) # Get the type of an individual actual argument (for *args # and **args this is the item type, not the collection type). actual_type = get_actual_type(arg_type, arg_kinds[actual], tuple_counter) check_arg( actual_type, arg_type, arg_kinds[actual], callee.arg_types[i], actual + 1, i + 1, callee, context, messages, ) # There may be some remaining tuple varargs items that haven't # been checked yet. Handle them. if ( callee.arg_kinds[i] == nodes.ARG_STAR and arg_kinds[actual] == nodes.ARG_STAR and isinstance(arg_types[actual], TupleType) ): tuplet = cast(TupleType, arg_types[actual]) while tuple_counter[0] < len(tuplet.items): actual_type = get_actual_type( arg_type, arg_kinds[actual], tuple_counter ) check_arg( actual_type, arg_type, arg_kinds[actual], callee.arg_types[i], actual + 1, i + 1, callee, context, messages, )
def check_argument_types( self, arg_types: List[Type], arg_kinds: List[int], callee: CallableType, formal_to_actual: List[List[int]], context: Context, messages: MessageBuilder = None, check_arg: ArgChecker = None, ) -> None: """Check argument types against a callable type. Report errors if the argument types are not compatible. """ messages = messages or self.msg check_arg = check_arg or self.check_arg # Keep track of consumed tuple *arg items. tuple_counter = [0] for i, actuals in enumerate(formal_to_actual): for actual in actuals: arg_type = arg_types[actual] # Check that a *arg is valid as varargs. if arg_kinds[actual] == nodes.ARG_STAR and not self.is_valid_var_arg( arg_type ): messages.invalid_var_arg(arg_type, context) if arg_kinds[ actual ] == nodes.ARG_STAR2 and not self.is_valid_keyword_var_arg(arg_type): messages.invalid_keyword_var_arg(arg_type, context) # Get the type of an individual actual argument (for *args # and **args this is the item type, not the collection type). actual_type = get_actual_type(arg_type, arg_kinds[actual], tuple_counter) check_arg( actual_type, arg_type, arg_kinds[actual], callee.arg_types[i], actual + 1, i + 1, callee, context, messages, ) # There may be some remaining tuple varargs items that haven't # been checked yet. Handle them. if ( callee.arg_kinds[i] == nodes.ARG_STAR and arg_kinds[actual] == nodes.ARG_STAR and isinstance(arg_types[actual], TupleType) ): tuplet = cast(TupleType, arg_types[actual]) while tuple_counter[0] < len(tuplet.items): actual_type = get_actual_type( arg_type, arg_kinds[actual], tuple_counter ) check_arg( actual_type, arg_type, arg_kinds[actual], callee.arg_types[i], actual + 1, i + 1, callee, context, messages, )
https://github.com/python/mypy/issues/1890
Traceback (most recent call last): File "/usr/local/Cellar/python3/3.5.1/Frameworks/Python.framework/Versions/3.5/lib/python3.5/runpy.py", line 170, in _run_module_as_main "__main__", mod_spec) File "/usr/local/Cellar/python3/3.5.1/Frameworks/Python.framework/Versions/3.5/lib/python3.5/runpy.py", line 85, in _run_code exec(code, run_globals) File "/usr/local/lib/python3.5/site-packages/mypy/__main__.py", line 5, in <module> main(None) File "/usr/local/lib/python3.5/site-packages/mypy/main.py", line 40, in main res = type_check_only(sources, bin_dir, options) File "/usr/local/lib/python3.5/site-packages/mypy/main.py", line 81, in type_check_only options=options) File "/usr/local/lib/python3.5/site-packages/mypy/build.py", line 177, in build dispatch(sources, manager) File "/usr/local/lib/python3.5/site-packages/mypy/build.py", line 1323, in dispatch process_graph(graph, manager) File "/usr/local/lib/python3.5/site-packages/mypy/build.py", line 1461, in process_graph process_stale_scc(graph, scc) File "/usr/local/lib/python3.5/site-packages/mypy/build.py", line 1538, in process_stale_scc graph[id].type_check() File "/usr/local/lib/python3.5/site-packages/mypy/build.py", line 1301, in type_check manager.type_checker.visit_file(self.tree, self.xpath) File "/usr/local/lib/python3.5/site-packages/mypy/checker.py", line 152, in visit_file self.accept(d) File "/usr/local/lib/python3.5/site-packages/mypy/checker.py", line 201, in accept typ = node.accept(self) File "/usr/local/lib/python3.5/site-packages/mypy/nodes.py", line 737, in accept return visitor.visit_expression_stmt(self) File "/usr/local/lib/python3.5/site-packages/mypy/checker.py", line 1333, in visit_expression_stmt self.accept(s.expr) File "/usr/local/lib/python3.5/site-packages/mypy/checker.py", line 201, in accept typ = node.accept(self) File "/usr/local/lib/python3.5/site-packages/mypy/nodes.py", line 1445, in accept return visitor.visit_list_expr(self) File "/usr/local/lib/python3.5/site-packages/mypy/checker.py", line 1859, in visit_list_expr return self.expr_checker.visit_list_expr(e) File "/usr/local/lib/python3.5/site-packages/mypy/checkexpr.py", line 1283, in visit_list_expr e) File "/usr/local/lib/python3.5/site-packages/mypy/checkexpr.py", line 1303, in check_list_or_set_expr [nodes.ARG_POS] * len(items), context)[0] File "/usr/local/lib/python3.5/site-packages/mypy/checkexpr.py", line 253, in check_call messages=arg_messages) File "/usr/local/lib/python3.5/site-packages/mypy/checkexpr.py", line 677, in check_argument_types actual + 1, i + 1, callee, context, messages) File "/usr/local/lib/python3.5/site-packages/mypy/checkexpr.py", line 702, in check_arg elif not is_subtype(caller_type, callee_type): File "/usr/local/lib/python3.5/site-packages/mypy/subtypes.py", line 51, in is_subtype return left.accept(SubtypeVisitor(right, type_parameter_checker)) AttributeError: 'NoneType' object has no attribute 'accept' *** INTERNAL ERROR *** unpacking.py:3: error: Internal error -- please report a bug at https://github.com/python/mypy/issues NOTE: you can use "mypy --pdb ..." to drop into the debugger when this happens.
AttributeError
def map_actuals_to_formals( caller_kinds: List[int], caller_names: List[str], callee_kinds: List[int], callee_names: List[str], caller_arg_type: Callable[[int], Type], ) -> List[List[int]]: """Calculate mapping between actual (caller) args and formals. The result contains a list of caller argument indexes mapping to each callee argument index, indexed by callee index. The caller_arg_type argument should evaluate to the type of the actual argument type with the given index. """ ncallee = len(callee_kinds) map = [[] for i in range(ncallee)] # type: List[List[int]] j = 0 for i, kind in enumerate(caller_kinds): if kind == nodes.ARG_POS: if j < ncallee: if callee_kinds[j] in [nodes.ARG_POS, nodes.ARG_OPT, nodes.ARG_NAMED]: map[j].append(i) j += 1 elif callee_kinds[j] == nodes.ARG_STAR: map[j].append(i) elif kind == nodes.ARG_STAR: # We need to know the actual type to map varargs. argt = caller_arg_type(i) if isinstance(argt, TupleType): # A tuple actual maps to a fixed number of formals. for _ in range(len(argt.items)): if j < ncallee: if callee_kinds[j] != nodes.ARG_STAR2: map[j].append(i) else: break j += 1 else: # Assume that it is an iterable (if it isn't, there will be # an error later). while j < ncallee: if callee_kinds[j] in (nodes.ARG_NAMED, nodes.ARG_STAR2): break else: map[j].append(i) j += 1 elif kind == nodes.ARG_NAMED: name = caller_names[i] if name in callee_names: map[callee_names.index(name)].append(i) elif nodes.ARG_STAR2 in callee_kinds: map[callee_kinds.index(nodes.ARG_STAR2)].append(i) else: assert kind == nodes.ARG_STAR2 for j in range(ncallee): # TODO tuple varargs complicate this no_certain_match = ( not map[j] or caller_kinds[map[j][0]] == nodes.ARG_STAR ) if (callee_names[j] and no_certain_match) or callee_kinds[ j ] == nodes.ARG_STAR2: map[j].append(i) return map
def map_actuals_to_formals( caller_kinds: List[int], caller_names: List[str], callee_kinds: List[int], callee_names: List[str], caller_arg_type: Callable[[int], Type], ) -> List[List[int]]: """Calculate mapping between actual (caller) args and formals. The result contains a list of caller argument indexes mapping to each callee argument index, indexed by callee index. The caller_arg_type argument should evaluate to the type of the actual argument type with the given index. """ ncallee = len(callee_kinds) map = [None] * ncallee # type: List[List[int]] for i in range(ncallee): map[i] = [] j = 0 for i, kind in enumerate(caller_kinds): if kind == nodes.ARG_POS: if j < ncallee: if callee_kinds[j] in [nodes.ARG_POS, nodes.ARG_OPT, nodes.ARG_NAMED]: map[j].append(i) j += 1 elif callee_kinds[j] == nodes.ARG_STAR: map[j].append(i) elif kind == nodes.ARG_STAR: # We need to know the actual type to map varargs. argt = caller_arg_type(i) if isinstance(argt, TupleType): # A tuple actual maps to a fixed number of formals. for _ in range(len(argt.items)): if j < ncallee: if callee_kinds[j] != nodes.ARG_STAR2: map[j].append(i) else: raise NotImplementedError() j += 1 else: # Assume that it is an iterable (if it isn't, there will be # an error later). while j < ncallee: if callee_kinds[j] in (nodes.ARG_NAMED, nodes.ARG_STAR2): break else: map[j].append(i) j += 1 elif kind == nodes.ARG_NAMED: name = caller_names[i] if name in callee_names: map[callee_names.index(name)].append(i) elif nodes.ARG_STAR2 in callee_kinds: map[callee_kinds.index(nodes.ARG_STAR2)].append(i) else: assert kind == nodes.ARG_STAR2 for j in range(ncallee): # TODO tuple varargs complicate this no_certain_match = ( not map[j] or caller_kinds[map[j][0]] == nodes.ARG_STAR ) if (callee_names[j] and no_certain_match) or callee_kinds[ j ] == nodes.ARG_STAR2: map[j].append(i) return map
https://github.com/python/mypy/issues/1553
Traceback (most recent call last): File "./.tox/mypy/bin/mypy", line 6, in <module> main(__file__) File ".../mypy/main.py", line 54, in main res = type_check_only(sources, bin_dir, options) File ".../mypy/main.py", line 102, in type_check_only python_path=options.python_path) File ".../mypy/build.py", line 209, in build dispatch(sources, manager) File ".../mypy/build.py", line 1321, in dispatch process_graph(graph, manager) File ".../mypy/build.py", line 1452, in process_graph process_stale_scc(graph, scc) File ".../mypy/build.py", line 1482, in process_stale_scc graph[id].type_check() File ".../mypy/build.py", line 1301, in type_check manager.type_checker.visit_file(self.tree, self.xpath) File ".../mypy/checker.py", line 419, in visit_file self.accept(d) File ".../mypy/checker.py", line 460, in accept typ = node.accept(self) File ".../mypy/nodes.py", line 650, in accept return visitor.visit_class_def(self) File ".../mypy/checker.py", line 1049, in visit_class_def self.accept(defn.defs) File ".../mypy/checker.py", line 460, in accept typ = node.accept(self) File ".../mypy/nodes.py", line 715, in accept return visitor.visit_block(self) File ".../mypy/checker.py", line 1144, in visit_block self.accept(s) File ".../mypy/checker.py", line 460, in accept typ = node.accept(self) File ".../mypy/nodes.py", line 531, in accept return visitor.visit_decorator(self) File ".../mypy/checker.py", line 1934, in visit_decorator e.func.accept(self) File ".../mypy/nodes.py", line 462, in accept return visitor.visit_func_def(self) File ".../mypy/checker.py", line 573, in visit_func_def self.check_func_item(defn, name=defn.name()) File ".../mypy/checker.py", line 631, in check_func_item self.check_func_def(defn, typ, name) File ".../mypy/checker.py", line 739, in check_func_def self.accept_in_frame(item.body) File ".../mypy/checker.py", line 475, in accept_in_frame answer = self.accept(node, type_context) File ".../mypy/checker.py", line 460, in accept typ = node.accept(self) File ".../mypy/nodes.py", line 715, in accept return visitor.visit_block(self) File ".../mypy/checker.py", line 1144, in visit_block self.accept(s) File ".../mypy/checker.py", line 460, in accept typ = node.accept(self) File ".../mypy/nodes.py", line 753, in accept return visitor.visit_assignment_stmt(self) File ".../mypy/checker.py", line 1153, in visit_assignment_stmt self.check_assignment(s.lvalues[-1], s.rvalue, s.type is None) File ".../mypy/checker.py", line 1203, in check_assignment self.infer_variable_type(inferred, lvalue, self.accept(rvalue), File ".../mypy/checker.py", line 460, in accept typ = node.accept(self) File ".../mypy/nodes.py", line 1185, in accept return visitor.visit_call_expr(self) File ".../mypy/checker.py", line 1992, in visit_call_expr return self.expr_checker.visit_call_expr(e) File ".../mypy/checkexpr.py", line 141, in visit_call_expr return self.check_call_expr_with_callee_type(callee_type, e) File ".../mypy/checkexpr.py", line 192, in check_call_expr_with_callee_type e.arg_names, callable_node=e.callee)[0] File ".../mypy/checkexpr.py", line 226, in check_call lambda i: self.accept(args[i])) File ".../mypy/checkexpr.py", line 1570, in map_actuals_to_formals raise NotImplementedError() NotImplementedError: *** INTERNAL ERROR *** qutebrowser/browser/webpage.py:344: error: Internal error -- please report a bug at https://github.com/python/mypy/issues
NotImplementedError
def visit_erased_type(self, left: ErasedType) -> bool: # We can get here when isinstance is used inside a lambda # whose type is being inferred. In any event, we have no reason # to think that an ErasedType will end up being the same as # any other type, even another ErasedType. return False
def visit_erased_type(self, left: ErasedType) -> bool: # Should not get here. raise RuntimeError()
https://github.com/python/mypy/issues/1607
$ python3 -m mypy --py2 rt6.py Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/runpy.py", line 170, in _run_module_as_main "__main__", mod_spec) File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/runpy.py", line 85, in _run_code exec(code, run_globals) File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/mypy/__main__.py", line 5, in <module> main(None) File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/mypy/main.py", line 54, in main res = type_check_only(sources, bin_dir, options) File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/mypy/main.py", line 102, in type_check_only python_path=options.python_path) File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/mypy/build.py", line 209, in build dispatch(sources, manager) File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/mypy/build.py", line 1255, in dispatch process_graph(graph, manager) File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/mypy/build.py", line 1386, in process_graph process_stale_scc(graph, scc) File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/mypy/build.py", line 1416, in process_stale_scc graph[id].type_check() File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/mypy/build.py", line 1235, in type_check manager.type_checker.visit_file(self.tree, self.xpath) File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/mypy/checker.py", line 419, in visit_file self.accept(d) File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/mypy/checker.py", line 460, in accept typ = node.accept(self) File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/mypy/nodes.py", line 462, in accept return visitor.visit_func_def(self) File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/mypy/checker.py", line 573, in visit_func_def self.check_func_item(defn, name=defn.name()) File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/mypy/checker.py", line 631, in check_func_item self.check_func_def(defn, typ, name) File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/mypy/checker.py", line 739, in check_func_def self.accept_in_frame(item.body) File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/mypy/checker.py", line 475, in accept_in_frame answer = self.accept(node, type_context) File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/mypy/checker.py", line 460, in accept typ = node.accept(self) File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/mypy/nodes.py", line 715, in accept return visitor.visit_block(self) File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/mypy/checker.py", line 1132, in visit_block self.accept(s) File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/mypy/checker.py", line 460, in accept typ = node.accept(self) File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/mypy/nodes.py", line 753, in accept return visitor.visit_assignment_stmt(self) File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/mypy/checker.py", line 1141, in visit_assignment_stmt self.check_assignment(s.lvalues[-1], s.rvalue, s.type is None) File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/mypy/checker.py", line 1191, in check_assignment self.infer_variable_type(inferred, lvalue, self.accept(rvalue), File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/mypy/checker.py", line 460, in accept typ = node.accept(self) File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/mypy/nodes.py", line 1174, in accept return visitor.visit_call_expr(self) File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/mypy/checker.py", line 1980, in visit_call_expr return self.expr_checker.visit_call_expr(e) File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/mypy/checkexpr.py", line 141, in visit_call_expr return self.check_call_expr_with_callee_type(callee_type, e) File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/mypy/checkexpr.py", line 192, in check_call_expr_with_callee_type e.arg_names, callable_node=e.callee)[0] File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/mypy/checkexpr.py", line 232, in check_call callee, args, arg_kinds, formal_to_actual, context) File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/mypy/checkexpr.py", line 400, in infer_function_type_arguments callee_type, args, arg_kinds, formal_to_actual) File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/mypy/checkexpr.py", line 330, in infer_arg_types_in_context2 res[ai] = self.accept(args[ai], callee.arg_types[i]) File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/mypy/checkexpr.py", line 1458, in accept return self.chk.accept(node, context) File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/mypy/checker.py", line 460, in accept typ = node.accept(self) File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/mypy/nodes.py", line 1396, in accept return visitor.visit_func_expr(self) File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/mypy/checker.py", line 2105, in visit_func_expr return self.expr_checker.visit_func_expr(e) File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/mypy/checkexpr.py", line 1269, in visit_func_expr self.chk.check_func_item(e, type_override=inferred_type) File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/mypy/checker.py", line 631, in check_func_item self.check_func_def(defn, typ, name) File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/mypy/checker.py", line 739, in check_func_def self.accept_in_frame(item.body) File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/mypy/checker.py", line 475, in accept_in_frame answer = self.accept(node, type_context) File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/mypy/checker.py", line 460, in accept typ = node.accept(self) File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/mypy/nodes.py", line 715, in accept return visitor.visit_block(self) File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/mypy/checker.py", line 1132, in visit_block self.accept(s) File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/mypy/checker.py", line 460, in accept typ = node.accept(self) File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/mypy/nodes.py", line 812, in accept return visitor.visit_return_stmt(self) File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/mypy/checker.py", line 1566, in visit_return_stmt typ = self.accept(s.expr, return_type) File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/mypy/checker.py", line 460, in accept typ = node.accept(self) File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/mypy/nodes.py", line 1443, in accept return visitor.visit_tuple_expr(self) File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/mypy/checker.py", line 2096, in visit_tuple_expr return self.expr_checker.visit_tuple_expr(e) File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/mypy/checkexpr.py", line 1221, in visit_tuple_expr tt = self.accept(item) File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/mypy/checkexpr.py", line 1458, in accept return self.chk.accept(node, context) File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/mypy/checker.py", line 460, in accept typ = node.accept(self) File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/mypy/nodes.py", line 1538, in accept return visitor.visit_conditional_expr(self) File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/mypy/checker.py", line 2123, in visit_conditional_expr return self.expr_checker.visit_conditional_expr(e) File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/mypy/checkexpr.py", line 1415, in visit_conditional_expr self.chk.typing_mode_weak()) File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/mypy/checker.py", line 2350, in find_isinstance_check if is_proper_subtype(vartype, type): File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/mypy/subtypes.py", line 352, in is_proper_subtype return sametypes.is_same_type(t, s) File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/mypy/sametypes.py", line 27, in is_same_type return left.accept(SameTypeVisitor(right)) File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/mypy/types.py", line 244, in accept return visitor.visit_erased_type(self) File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/mypy/sametypes.py", line 74, in visit_erased_type raise RuntimeError() RuntimeError: *** INTERNAL ERROR *** rt6.py:7: error: Internal error -- please report a bug at https://github.com/python/mypy/issues
RuntimeError
def visit_break_stmt(self, s: BreakStmt) -> None: if self.loop_depth == 0: self.fail("'break' outside loop", s, True, blocker=True)
def visit_break_stmt(self, s: BreakStmt) -> None: if self.loop_depth == 0: self.fail("'break' outside loop", s, True)
https://github.com/python/mypy/issues/1571
Traceback (most recent call last): File "/Users/rbarton/mypy/scripts/mypy", line 6, in <module> main(__file__) [...] File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/mypy/checker.py", line 2028, in visit_break_stmt self.binder.allow_jump(self.binder.loop_frames[-1] - 1) IndexError: list index out of range *** INTERNAL ERROR *** break.py:1: error: Internal error -- please report a bug at https://github.com/python/mypy/issues NOTE: you can use "mypy --pdb ..." to drop into the debugger when this happens.
IndexError
def visit_continue_stmt(self, s: ContinueStmt) -> None: if self.loop_depth == 0: self.fail("'continue' outside loop", s, True, blocker=True)
def visit_continue_stmt(self, s: ContinueStmt) -> None: if self.loop_depth == 0: self.fail("'continue' outside loop", s, True)
https://github.com/python/mypy/issues/1571
Traceback (most recent call last): File "/Users/rbarton/mypy/scripts/mypy", line 6, in <module> main(__file__) [...] File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/mypy/checker.py", line 2028, in visit_break_stmt self.binder.allow_jump(self.binder.loop_frames[-1] - 1) IndexError: list index out of range *** INTERNAL ERROR *** break.py:1: error: Internal error -- please report a bug at https://github.com/python/mypy/issues NOTE: you can use "mypy --pdb ..." to drop into the debugger when this happens.
IndexError
def visit_yield_from_expr(self, e: YieldFromExpr) -> None: if not self.is_func_scope(): # not sure self.fail("'yield from' outside function", e, True, blocker=True) else: self.function_stack[-1].is_generator = True if e.expr: e.expr.accept(self)
def visit_yield_from_expr(self, e: YieldFromExpr) -> None: if not self.is_func_scope(): # not sure self.fail("'yield from' outside function", e) else: self.function_stack[-1].is_generator = True if e.expr: e.expr.accept(self)
https://github.com/python/mypy/issues/1571
Traceback (most recent call last): File "/Users/rbarton/mypy/scripts/mypy", line 6, in <module> main(__file__) [...] File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/mypy/checker.py", line 2028, in visit_break_stmt self.binder.allow_jump(self.binder.loop_frames[-1] - 1) IndexError: list index out of range *** INTERNAL ERROR *** break.py:1: error: Internal error -- please report a bug at https://github.com/python/mypy/issues NOTE: you can use "mypy --pdb ..." to drop into the debugger when this happens.
IndexError
def visit_yield_expr(self, expr: YieldExpr) -> None: if not self.is_func_scope(): self.fail("'yield' outside function", expr, True, blocker=True) else: self.function_stack[-1].is_generator = True if expr.expr: expr.expr.accept(self)
def visit_yield_expr(self, expr: YieldExpr) -> None: if not self.is_func_scope(): self.fail("'yield' outside function", expr) else: self.function_stack[-1].is_generator = True if expr.expr: expr.expr.accept(self)
https://github.com/python/mypy/issues/1571
Traceback (most recent call last): File "/Users/rbarton/mypy/scripts/mypy", line 6, in <module> main(__file__) [...] File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/mypy/checker.py", line 2028, in visit_break_stmt self.binder.allow_jump(self.binder.loop_frames[-1] - 1) IndexError: list index out of range *** INTERNAL ERROR *** break.py:1: error: Internal error -- please report a bug at https://github.com/python/mypy/issues NOTE: you can use "mypy --pdb ..." to drop into the debugger when this happens.
IndexError
def fail( self, msg: str, ctx: Context, serious: bool = False, *, blocker: bool = False ) -> None: if ( not serious and not self.check_untyped_defs and self.function_stack and self.function_stack[-1].is_dynamic() ): return self.errors.report(ctx.get_line(), msg, blocker=blocker)
def fail(self, msg: str, ctx: Context, serious: bool = False) -> None: if ( not serious and not self.check_untyped_defs and self.function_stack and self.function_stack[-1].is_dynamic() ): return self.errors.report(ctx.get_line(), msg)
https://github.com/python/mypy/issues/1571
Traceback (most recent call last): File "/Users/rbarton/mypy/scripts/mypy", line 6, in <module> main(__file__) [...] File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/mypy/checker.py", line 2028, in visit_break_stmt self.binder.allow_jump(self.binder.loop_frames[-1] - 1) IndexError: list index out of range *** INTERNAL ERROR *** break.py:1: error: Internal error -- please report a bug at https://github.com/python/mypy/issues NOTE: you can use "mypy --pdb ..." to drop into the debugger when this happens.
IndexError
def read_with_python_encoding(path: str, pyversion: Tuple[int, int]) -> str: """Read the Python file with while obeying PEP-263 encoding detection""" source_bytearray = bytearray() encoding = "utf8" if pyversion[0] >= 3 else "ascii" with open(path, "rb") as f: # read first two lines and check if PEP-263 coding is present source_bytearray.extend(f.readline()) source_bytearray.extend(f.readline()) # check for BOM UTF-8 encoding and strip it out if present if source_bytearray.startswith(b"\xef\xbb\xbf"): encoding = "utf8" source_bytearray = source_bytearray[3:] else: _encoding, _ = util.find_python_encoding(source_bytearray, pyversion) # check that the coding isn't mypy. We skip it since # registering may not have happened yet if _encoding != "mypy": encoding = _encoding source_bytearray.extend(f.read()) try: source_bytearray.decode(encoding) except LookupError as lookuperr: raise DecodeError(str(lookuperr)) return source_bytearray.decode(encoding)
def read_with_python_encoding(path: str, pyversion: Tuple[int, int]) -> str: """Read the Python file with while obeying PEP-263 encoding detection""" source_bytearray = bytearray() encoding = "utf8" if pyversion[0] >= 3 else "ascii" with open(path, "rb") as f: # read first two lines and check if PEP-263 coding is present source_bytearray.extend(f.readline()) source_bytearray.extend(f.readline()) # check for BOM UTF-8 encoding and strip it out if present if source_bytearray.startswith(b"\xef\xbb\xbf"): encoding = "utf8" source_bytearray = source_bytearray[3:] else: _encoding, _ = util.find_python_encoding(source_bytearray, pyversion) # check that the coding isn't mypy. We skip it since # registering may not have happened yet if _encoding != "mypy": encoding = _encoding source_bytearray.extend(f.read()) return source_bytearray.decode(encoding)
https://github.com/python/mypy/issues/1521
9.796:LOG: Parsing Lib/test/bad_coding.py (test.bad_coding) Traceback (most recent call last): File "/usr/local/bin/mypy", line 6, in <module> main(__file__) File "/usr/local/lib/python3.2/site-packages/mypy/main.py", line 54, in main res = type_check_only(sources, bin_dir, options) File "/usr/local/lib/python3.2/site-packages/mypy/main.py", line 102, in type_check_only python_path=options.python_path) File "/usr/local/lib/python3.2/site-packages/mypy/build.py", line 209, in build dispatch(sources, manager) File "/usr/local/lib/python3.2/site-packages/mypy/build.py", line 1253, in dispatch graph = load_graph(sources, manager) File "/usr/local/lib/python3.2/site-packages/mypy/build.py", line 1268, in load_graph st = State(id=bs.module, path=bs.path, source=bs.text, manager=manager) File "/usr/local/lib/python3.2/site-packages/mypy/build.py", line 1040, in __init__ self.parse_file() File "/usr/local/lib/python3.2/site-packages/mypy/build.py", line 1151, in parse_file self.tree = manager.parse_file(self.id, self.xpath, source) File "/usr/local/lib/python3.2/contextlib.py", line 66, in __exit__ self.gen.throw(type, value, traceback) File "/usr/local/lib/python3.2/site-packages/mypy/build.py", line 1105, in wrap_context yield File "/usr/local/lib/python3.2/site-packages/mypy/build.py", line 1144, in parse_file source = read_with_python_encoding(self.path, manager.pyversion) File "/usr/local/lib/python3.2/site-packages/mypy/build.py", line 640, in read_with_python_encoding return source_bytearray.decode(encoding) LookupError: unknown encoding: uft-8 *** INTERNAL ERROR *** Lib/test/bad_coding.py: error: Internal error -- please report a bug at https://github.com/python/mypy/issues
LookupError
def parse_file(self) -> None: if self.tree is not None: # The file was already parsed (in __init__()). return manager = self.manager modules = manager.modules manager.log("Parsing %s (%s)" % (self.xpath, self.id)) with self.wrap_context(): source = self.source self.source = None # We won't need it again. if self.path and source is None: try: source = read_with_python_encoding(self.path, manager.pyversion) except IOError as ioerr: raise CompileError( ["mypy: can't read file '{}': {}".format(self.path, ioerr.strerror)] ) except (UnicodeDecodeError, DecodeError) as decodeerr: raise CompileError( [ "mypy: can't decode file '{}': {}".format( self.path, str(decodeerr) ) ] ) self.tree = manager.parse_file(self.id, self.xpath, source) modules[self.id] = self.tree # Do the first pass of semantic analysis: add top-level # definitions in the file to the symbol table. We must do # this before processing imports, since this may mark some # import statements as unreachable. first = FirstPass(manager.semantic_analyzer) first.analyze(self.tree, self.xpath, self.id) # Initialize module symbol table, which was populated by the # semantic analyzer. # TODO: Why can't FirstPass .analyze() do this? self.tree.names = manager.semantic_analyzer.globals # Compute (direct) dependencies. # Add all direct imports (this is why we needed the first pass). # Also keep track of each dependency's source line. dependencies = [] suppressed = [] dep_line_map = {} # type: Dict[str, int] # id -> line for id, line in manager.all_imported_modules_in_file(self.tree): if id == self.id: continue # Omit missing modules, as otherwise we could not type-check # programs with missing modules. if id in manager.missing_modules: if id not in dep_line_map: suppressed.append(id) dep_line_map[id] = line continue if id == "": # Must be from a relative import. manager.errors.set_file(self.xpath) manager.errors.report( line, "No parent module -- cannot perform relative import", blocker=True ) continue if id not in dep_line_map: dependencies.append(id) dep_line_map[id] = line # Every module implicitly depends on builtins. if self.id != "builtins" and "builtins" not in dep_line_map: dependencies.append("builtins") # If self.dependencies is already set, it was read from the # cache, but for some reason we're re-parsing the file. # NOTE: What to do about race conditions (like editing the # file while mypy runs)? A previous version of this code # explicitly checked for this, but ran afoul of other reasons # for differences (e.g. --silent-imports). self.dependencies = dependencies self.suppressed = suppressed self.dep_line_map = dep_line_map self.check_blockers()
def parse_file(self) -> None: if self.tree is not None: # The file was already parsed (in __init__()). return manager = self.manager modules = manager.modules manager.log("Parsing %s (%s)" % (self.xpath, self.id)) with self.wrap_context(): source = self.source self.source = None # We won't need it again. if self.path and source is None: try: source = read_with_python_encoding(self.path, manager.pyversion) except IOError as ioerr: raise CompileError( ["mypy: can't read file '{}': {}".format(self.path, ioerr.strerror)] ) except UnicodeDecodeError as decodeerr: raise CompileError( [ "mypy: can't decode file '{}': {}".format( self.path, str(decodeerr) ) ] ) self.tree = manager.parse_file(self.id, self.xpath, source) modules[self.id] = self.tree # Do the first pass of semantic analysis: add top-level # definitions in the file to the symbol table. We must do # this before processing imports, since this may mark some # import statements as unreachable. first = FirstPass(manager.semantic_analyzer) first.analyze(self.tree, self.xpath, self.id) # Initialize module symbol table, which was populated by the # semantic analyzer. # TODO: Why can't FirstPass .analyze() do this? self.tree.names = manager.semantic_analyzer.globals # Compute (direct) dependencies. # Add all direct imports (this is why we needed the first pass). # Also keep track of each dependency's source line. dependencies = [] suppressed = [] dep_line_map = {} # type: Dict[str, int] # id -> line for id, line in manager.all_imported_modules_in_file(self.tree): if id == self.id: continue # Omit missing modules, as otherwise we could not type-check # programs with missing modules. if id in manager.missing_modules: if id not in dep_line_map: suppressed.append(id) dep_line_map[id] = line continue if id == "": # Must be from a relative import. manager.errors.set_file(self.xpath) manager.errors.report( line, "No parent module -- cannot perform relative import", blocker=True ) continue if id not in dep_line_map: dependencies.append(id) dep_line_map[id] = line # Every module implicitly depends on builtins. if self.id != "builtins" and "builtins" not in dep_line_map: dependencies.append("builtins") # If self.dependencies is already set, it was read from the # cache, but for some reason we're re-parsing the file. # NOTE: What to do about race conditions (like editing the # file while mypy runs)? A previous version of this code # explicitly checked for this, but ran afoul of other reasons # for differences (e.g. --silent-imports). self.dependencies = dependencies self.suppressed = suppressed self.dep_line_map = dep_line_map self.check_blockers()
https://github.com/python/mypy/issues/1521
9.796:LOG: Parsing Lib/test/bad_coding.py (test.bad_coding) Traceback (most recent call last): File "/usr/local/bin/mypy", line 6, in <module> main(__file__) File "/usr/local/lib/python3.2/site-packages/mypy/main.py", line 54, in main res = type_check_only(sources, bin_dir, options) File "/usr/local/lib/python3.2/site-packages/mypy/main.py", line 102, in type_check_only python_path=options.python_path) File "/usr/local/lib/python3.2/site-packages/mypy/build.py", line 209, in build dispatch(sources, manager) File "/usr/local/lib/python3.2/site-packages/mypy/build.py", line 1253, in dispatch graph = load_graph(sources, manager) File "/usr/local/lib/python3.2/site-packages/mypy/build.py", line 1268, in load_graph st = State(id=bs.module, path=bs.path, source=bs.text, manager=manager) File "/usr/local/lib/python3.2/site-packages/mypy/build.py", line 1040, in __init__ self.parse_file() File "/usr/local/lib/python3.2/site-packages/mypy/build.py", line 1151, in parse_file self.tree = manager.parse_file(self.id, self.xpath, source) File "/usr/local/lib/python3.2/contextlib.py", line 66, in __exit__ self.gen.throw(type, value, traceback) File "/usr/local/lib/python3.2/site-packages/mypy/build.py", line 1105, in wrap_context yield File "/usr/local/lib/python3.2/site-packages/mypy/build.py", line 1144, in parse_file source = read_with_python_encoding(self.path, manager.pyversion) File "/usr/local/lib/python3.2/site-packages/mypy/build.py", line 640, in read_with_python_encoding return source_bytearray.decode(encoding) LookupError: unknown encoding: uft-8 *** INTERNAL ERROR *** Lib/test/bad_coding.py: error: Internal error -- please report a bug at https://github.com/python/mypy/issues
LookupError
def overload_call_target( self, arg_types: List[Type], arg_kinds: List[int], arg_names: List[str], overload: Overloaded, context: Context, messages: MessageBuilder = None, ) -> Type: """Infer the correct overload item to call with given argument types. The return value may be CallableType or AnyType (if an unique item could not be determined). """ messages = messages or self.msg # TODO: For overlapping signatures we should try to get a more precise # result than 'Any'. match = [] # type: List[CallableType] best_match = 0 for typ in overload.items(): similarity = self.erased_signature_similarity( arg_types, arg_kinds, arg_names, typ, context=context ) if similarity > 0 and similarity >= best_match: if ( match and not is_same_type(match[-1].ret_type, typ.ret_type) and not mypy.checker.is_more_precise_signature(match[-1], typ) ): # Ambiguous return type. Either the function overload is # overlapping (which we don't handle very well here) or the # caller has provided some Any argument types; in either # case we'll fall back to Any. It's okay to use Any types # in calls. # # Overlapping overload items are generally fine if the # overlapping is only possible when there is multiple # inheritance, as this is rare. See docstring of # mypy.meet.is_overlapping_types for more about this. # # Note that there is no ambiguity if the items are # covariant in both argument types and return types with # respect to type precision. We'll pick the best/closest # match. # # TODO: Consider returning a union type instead if the # overlapping is NOT due to Any types? return AnyType() else: match.append(typ) best_match = max(best_match, similarity) if not match: messages.no_variant_matches_arguments(overload, arg_types, context) return AnyType() else: if len(match) == 1: return match[0] else: # More than one signature matches. Pick the first *non-erased* # matching signature, or default to the first one if none # match. for m in match: if self.match_signature_types( arg_types, arg_kinds, arg_names, m, context=context ): return m return match[0]
def overload_call_target( self, arg_types: List[Type], arg_kinds: List[int], arg_names: List[str], overload: Overloaded, context: Context, messages: MessageBuilder = None, ) -> Type: """Infer the correct overload item to call with given argument types. The return value may be CallableType or AnyType (if an unique item could not be determined). """ messages = messages or self.msg # TODO: For overlapping signatures we should try to get a more precise # result than 'Any'. match = [] # type: List[CallableType] best_match = 0 for typ in overload.items(): similarity = self.erased_signature_similarity( arg_types, arg_kinds, arg_names, typ ) if similarity > 0 and similarity >= best_match: if ( match and not is_same_type(match[-1].ret_type, typ.ret_type) and not mypy.checker.is_more_precise_signature(match[-1], typ) ): # Ambiguous return type. Either the function overload is # overlapping (which we don't handle very well here) or the # caller has provided some Any argument types; in either # case we'll fall back to Any. It's okay to use Any types # in calls. # # Overlapping overload items are generally fine if the # overlapping is only possible when there is multiple # inheritance, as this is rare. See docstring of # mypy.meet.is_overlapping_types for more about this. # # Note that there is no ambiguity if the items are # covariant in both argument types and return types with # respect to type precision. We'll pick the best/closest # match. # # TODO: Consider returning a union type instead if the # overlapping is NOT due to Any types? return AnyType() else: match.append(typ) best_match = max(best_match, similarity) if not match: messages.no_variant_matches_arguments(overload, arg_types, context) return AnyType() else: if len(match) == 1: return match[0] else: # More than one signature matches. Pick the first *non-erased* # matching signature, or default to the first one if none # match. for m in match: if self.match_signature_types(arg_types, arg_kinds, arg_names, m): return m return match[0]
https://github.com/python/mypy/issues/1564
Traceback (most recent call last): File "/usr/lib/python-exec/python3.4/mypy", line 6, in <module> main(__file__) File "/usr/lib64/python3.4/site-packages/mypy/main.py", line 54, in main res = type_check_only(sources, bin_dir, options) File "/usr/lib64/python3.4/site-packages/mypy/main.py", line 102, in type_check_only python_path=options.python_path) File "/usr/lib64/python3.4/site-packages/mypy/build.py", line 209, in build dispatch(sources, manager) File "/usr/lib64/python3.4/site-packages/mypy/build.py", line 1325, in dispatch process_graph(graph, manager) File "/usr/lib64/python3.4/site-packages/mypy/build.py", line 1456, in process_graph process_stale_scc(graph, scc) File "/usr/lib64/python3.4/site-packages/mypy/build.py", line 1486, in process_stale_scc graph[id].type_check() File "/usr/lib64/python3.4/site-packages/mypy/build.py", line 1305, in type_check manager.type_checker.visit_file(self.tree, self.xpath) File "/usr/lib64/python3.4/site-packages/mypy/checker.py", line 424, in visit_file self.accept(d) File "/usr/lib64/python3.4/site-packages/mypy/checker.py", line 465, in accept typ = node.accept(self) File "/usr/lib64/python3.4/site-packages/mypy/nodes.py", line 729, in accept return visitor.visit_expression_stmt(self) File "/usr/lib64/python3.4/site-packages/mypy/checker.py", line 1570, in visit_expression_stmt self.accept(s.expr) File "/usr/lib64/python3.4/site-packages/mypy/checker.py", line 465, in accept typ = node.accept(self) File "/usr/lib64/python3.4/site-packages/mypy/nodes.py", line 1185, in accept return visitor.visit_call_expr(self) File "/usr/lib64/python3.4/site-packages/mypy/checker.py", line 1997, in visit_call_expr return self.expr_checker.visit_call_expr(e) File "/usr/lib64/python3.4/site-packages/mypy/checkexpr.py", line 141, in visit_call_expr return self.check_call_expr_with_callee_type(callee_type, e) File "/usr/lib64/python3.4/site-packages/mypy/checkexpr.py", line 192, in check_call_expr_with_callee_type e.arg_names, callable_node=e.callee)[0] File "/usr/lib64/python3.4/site-packages/mypy/checkexpr.py", line 257, in check_call messages=arg_messages) File "/usr/lib64/python3.4/site-packages/mypy/checkexpr.py", line 666, in overload_call_target typ) File "/usr/lib64/python3.4/site-packages/mypy/checkexpr.py", line 742, in erased_signature_similarity None, check_arg=check_arg) File "/usr/lib64/python3.4/site-packages/mypy/checkexpr.py", line 614, in check_argument_types messages.invalid_keyword_var_arg(arg_type, context) File "/usr/lib64/python3.4/site-packages/mypy/messages.py", line 687, in invalid_keyword_var_arg context) File "/usr/lib64/python3.4/site-packages/mypy/messages.py", line 147, in fail self.report(msg, context, 'error', file=file) File "/usr/lib64/python3.4/site-packages/mypy/messages.py", line 143, in report self.errors.report(context.get_line(), msg.strip(), severity=severity, file=file) AttributeError: 'NoneType' object has no attribute 'get_line'
AttributeError
def erased_signature_similarity( self, arg_types: List[Type], arg_kinds: List[int], arg_names: List[str], callee: CallableType, context: Context, ) -> int: """Determine whether arguments could match the signature at runtime. Return similarity level (0 = no match, 1 = can match, 2 = non-promotion match). See overload_arg_similarity for a discussion of similarity levels. """ formal_to_actual = map_actuals_to_formals( arg_kinds, arg_names, callee.arg_kinds, callee.arg_names, lambda i: arg_types[i] ) if not self.check_argument_count( callee, arg_types, arg_kinds, arg_names, formal_to_actual, None, None ): # Too few or many arguments -> no match. return 0 similarity = 2 def check_arg( caller_type: Type, original_caller_type: Type, caller_kind: int, callee_type: Type, n: int, m: int, callee: CallableType, context: Context, messages: MessageBuilder, ) -> None: nonlocal similarity similarity = min(similarity, overload_arg_similarity(caller_type, callee_type)) if similarity == 0: # No match -- exit early since none of the remaining work can change # the result. raise Finished try: self.check_argument_types( arg_types, arg_kinds, callee, formal_to_actual, context=context, check_arg=check_arg, ) except Finished: pass return similarity
def erased_signature_similarity( self, arg_types: List[Type], arg_kinds: List[int], arg_names: List[str], callee: CallableType, ) -> int: """Determine whether arguments could match the signature at runtime. Return similarity level (0 = no match, 1 = can match, 2 = non-promotion match). See overload_arg_similarity for a discussion of similarity levels. """ formal_to_actual = map_actuals_to_formals( arg_kinds, arg_names, callee.arg_kinds, callee.arg_names, lambda i: arg_types[i] ) if not self.check_argument_count( callee, arg_types, arg_kinds, arg_names, formal_to_actual, None, None ): # Too few or many arguments -> no match. return 0 similarity = 2 def check_arg( caller_type: Type, original_caller_type: Type, caller_kind: int, callee_type: Type, n: int, m: int, callee: CallableType, context: Context, messages: MessageBuilder, ) -> None: nonlocal similarity similarity = min(similarity, overload_arg_similarity(caller_type, callee_type)) if similarity == 0: # No match -- exit early since none of the remaining work can change # the result. raise Finished try: self.check_argument_types( arg_types, arg_kinds, callee, formal_to_actual, None, check_arg=check_arg ) except Finished: pass return similarity
https://github.com/python/mypy/issues/1564
Traceback (most recent call last): File "/usr/lib/python-exec/python3.4/mypy", line 6, in <module> main(__file__) File "/usr/lib64/python3.4/site-packages/mypy/main.py", line 54, in main res = type_check_only(sources, bin_dir, options) File "/usr/lib64/python3.4/site-packages/mypy/main.py", line 102, in type_check_only python_path=options.python_path) File "/usr/lib64/python3.4/site-packages/mypy/build.py", line 209, in build dispatch(sources, manager) File "/usr/lib64/python3.4/site-packages/mypy/build.py", line 1325, in dispatch process_graph(graph, manager) File "/usr/lib64/python3.4/site-packages/mypy/build.py", line 1456, in process_graph process_stale_scc(graph, scc) File "/usr/lib64/python3.4/site-packages/mypy/build.py", line 1486, in process_stale_scc graph[id].type_check() File "/usr/lib64/python3.4/site-packages/mypy/build.py", line 1305, in type_check manager.type_checker.visit_file(self.tree, self.xpath) File "/usr/lib64/python3.4/site-packages/mypy/checker.py", line 424, in visit_file self.accept(d) File "/usr/lib64/python3.4/site-packages/mypy/checker.py", line 465, in accept typ = node.accept(self) File "/usr/lib64/python3.4/site-packages/mypy/nodes.py", line 729, in accept return visitor.visit_expression_stmt(self) File "/usr/lib64/python3.4/site-packages/mypy/checker.py", line 1570, in visit_expression_stmt self.accept(s.expr) File "/usr/lib64/python3.4/site-packages/mypy/checker.py", line 465, in accept typ = node.accept(self) File "/usr/lib64/python3.4/site-packages/mypy/nodes.py", line 1185, in accept return visitor.visit_call_expr(self) File "/usr/lib64/python3.4/site-packages/mypy/checker.py", line 1997, in visit_call_expr return self.expr_checker.visit_call_expr(e) File "/usr/lib64/python3.4/site-packages/mypy/checkexpr.py", line 141, in visit_call_expr return self.check_call_expr_with_callee_type(callee_type, e) File "/usr/lib64/python3.4/site-packages/mypy/checkexpr.py", line 192, in check_call_expr_with_callee_type e.arg_names, callable_node=e.callee)[0] File "/usr/lib64/python3.4/site-packages/mypy/checkexpr.py", line 257, in check_call messages=arg_messages) File "/usr/lib64/python3.4/site-packages/mypy/checkexpr.py", line 666, in overload_call_target typ) File "/usr/lib64/python3.4/site-packages/mypy/checkexpr.py", line 742, in erased_signature_similarity None, check_arg=check_arg) File "/usr/lib64/python3.4/site-packages/mypy/checkexpr.py", line 614, in check_argument_types messages.invalid_keyword_var_arg(arg_type, context) File "/usr/lib64/python3.4/site-packages/mypy/messages.py", line 687, in invalid_keyword_var_arg context) File "/usr/lib64/python3.4/site-packages/mypy/messages.py", line 147, in fail self.report(msg, context, 'error', file=file) File "/usr/lib64/python3.4/site-packages/mypy/messages.py", line 143, in report self.errors.report(context.get_line(), msg.strip(), severity=severity, file=file) AttributeError: 'NoneType' object has no attribute 'get_line'
AttributeError
def match_signature_types( self, arg_types: List[Type], arg_kinds: List[int], arg_names: List[str], callee: CallableType, context: Context, ) -> bool: """Determine whether arguments types match the signature. Assume that argument counts are compatible. Return True if arguments match. """ formal_to_actual = map_actuals_to_formals( arg_kinds, arg_names, callee.arg_kinds, callee.arg_names, lambda i: arg_types[i] ) ok = True def check_arg( caller_type: Type, original_caller_type: Type, caller_kind: int, callee_type: Type, n: int, m: int, callee: CallableType, context: Context, messages: MessageBuilder, ) -> None: nonlocal ok if not is_subtype(caller_type, callee_type): ok = False self.check_argument_types( arg_types, arg_kinds, callee, formal_to_actual, context=context, check_arg=check_arg, ) return ok
def match_signature_types( self, arg_types: List[Type], arg_kinds: List[int], arg_names: List[str], callee: CallableType, ) -> bool: """Determine whether arguments types match the signature. Assume that argument counts are compatible. Return True if arguments match. """ formal_to_actual = map_actuals_to_formals( arg_kinds, arg_names, callee.arg_kinds, callee.arg_names, lambda i: arg_types[i] ) ok = True def check_arg( caller_type: Type, original_caller_type: Type, caller_kind: int, callee_type: Type, n: int, m: int, callee: CallableType, context: Context, messages: MessageBuilder, ) -> None: nonlocal ok if not is_subtype(caller_type, callee_type): ok = False self.check_argument_types( arg_types, arg_kinds, callee, formal_to_actual, None, check_arg=check_arg ) return ok
https://github.com/python/mypy/issues/1564
Traceback (most recent call last): File "/usr/lib/python-exec/python3.4/mypy", line 6, in <module> main(__file__) File "/usr/lib64/python3.4/site-packages/mypy/main.py", line 54, in main res = type_check_only(sources, bin_dir, options) File "/usr/lib64/python3.4/site-packages/mypy/main.py", line 102, in type_check_only python_path=options.python_path) File "/usr/lib64/python3.4/site-packages/mypy/build.py", line 209, in build dispatch(sources, manager) File "/usr/lib64/python3.4/site-packages/mypy/build.py", line 1325, in dispatch process_graph(graph, manager) File "/usr/lib64/python3.4/site-packages/mypy/build.py", line 1456, in process_graph process_stale_scc(graph, scc) File "/usr/lib64/python3.4/site-packages/mypy/build.py", line 1486, in process_stale_scc graph[id].type_check() File "/usr/lib64/python3.4/site-packages/mypy/build.py", line 1305, in type_check manager.type_checker.visit_file(self.tree, self.xpath) File "/usr/lib64/python3.4/site-packages/mypy/checker.py", line 424, in visit_file self.accept(d) File "/usr/lib64/python3.4/site-packages/mypy/checker.py", line 465, in accept typ = node.accept(self) File "/usr/lib64/python3.4/site-packages/mypy/nodes.py", line 729, in accept return visitor.visit_expression_stmt(self) File "/usr/lib64/python3.4/site-packages/mypy/checker.py", line 1570, in visit_expression_stmt self.accept(s.expr) File "/usr/lib64/python3.4/site-packages/mypy/checker.py", line 465, in accept typ = node.accept(self) File "/usr/lib64/python3.4/site-packages/mypy/nodes.py", line 1185, in accept return visitor.visit_call_expr(self) File "/usr/lib64/python3.4/site-packages/mypy/checker.py", line 1997, in visit_call_expr return self.expr_checker.visit_call_expr(e) File "/usr/lib64/python3.4/site-packages/mypy/checkexpr.py", line 141, in visit_call_expr return self.check_call_expr_with_callee_type(callee_type, e) File "/usr/lib64/python3.4/site-packages/mypy/checkexpr.py", line 192, in check_call_expr_with_callee_type e.arg_names, callable_node=e.callee)[0] File "/usr/lib64/python3.4/site-packages/mypy/checkexpr.py", line 257, in check_call messages=arg_messages) File "/usr/lib64/python3.4/site-packages/mypy/checkexpr.py", line 666, in overload_call_target typ) File "/usr/lib64/python3.4/site-packages/mypy/checkexpr.py", line 742, in erased_signature_similarity None, check_arg=check_arg) File "/usr/lib64/python3.4/site-packages/mypy/checkexpr.py", line 614, in check_argument_types messages.invalid_keyword_var_arg(arg_type, context) File "/usr/lib64/python3.4/site-packages/mypy/messages.py", line 687, in invalid_keyword_var_arg context) File "/usr/lib64/python3.4/site-packages/mypy/messages.py", line 147, in fail self.report(msg, context, 'error', file=file) File "/usr/lib64/python3.4/site-packages/mypy/messages.py", line 143, in report self.errors.report(context.get_line(), msg.strip(), severity=severity, file=file) AttributeError: 'NoneType' object has no attribute 'get_line'
AttributeError
def report(self, msg: str, context: Context, severity: str, file: str = None) -> None: """Report an error or note (unless disabled).""" if self.disable_count <= 0: self.errors.report( context.get_line() if context else -1, msg.strip(), severity=severity, file=file, )
def report(self, msg: str, context: Context, severity: str, file: str = None) -> None: """Report an error or note (unless disabled).""" if self.disable_count <= 0: self.errors.report( context.get_line(), msg.strip(), severity=severity, file=file )
https://github.com/python/mypy/issues/1564
Traceback (most recent call last): File "/usr/lib/python-exec/python3.4/mypy", line 6, in <module> main(__file__) File "/usr/lib64/python3.4/site-packages/mypy/main.py", line 54, in main res = type_check_only(sources, bin_dir, options) File "/usr/lib64/python3.4/site-packages/mypy/main.py", line 102, in type_check_only python_path=options.python_path) File "/usr/lib64/python3.4/site-packages/mypy/build.py", line 209, in build dispatch(sources, manager) File "/usr/lib64/python3.4/site-packages/mypy/build.py", line 1325, in dispatch process_graph(graph, manager) File "/usr/lib64/python3.4/site-packages/mypy/build.py", line 1456, in process_graph process_stale_scc(graph, scc) File "/usr/lib64/python3.4/site-packages/mypy/build.py", line 1486, in process_stale_scc graph[id].type_check() File "/usr/lib64/python3.4/site-packages/mypy/build.py", line 1305, in type_check manager.type_checker.visit_file(self.tree, self.xpath) File "/usr/lib64/python3.4/site-packages/mypy/checker.py", line 424, in visit_file self.accept(d) File "/usr/lib64/python3.4/site-packages/mypy/checker.py", line 465, in accept typ = node.accept(self) File "/usr/lib64/python3.4/site-packages/mypy/nodes.py", line 729, in accept return visitor.visit_expression_stmt(self) File "/usr/lib64/python3.4/site-packages/mypy/checker.py", line 1570, in visit_expression_stmt self.accept(s.expr) File "/usr/lib64/python3.4/site-packages/mypy/checker.py", line 465, in accept typ = node.accept(self) File "/usr/lib64/python3.4/site-packages/mypy/nodes.py", line 1185, in accept return visitor.visit_call_expr(self) File "/usr/lib64/python3.4/site-packages/mypy/checker.py", line 1997, in visit_call_expr return self.expr_checker.visit_call_expr(e) File "/usr/lib64/python3.4/site-packages/mypy/checkexpr.py", line 141, in visit_call_expr return self.check_call_expr_with_callee_type(callee_type, e) File "/usr/lib64/python3.4/site-packages/mypy/checkexpr.py", line 192, in check_call_expr_with_callee_type e.arg_names, callable_node=e.callee)[0] File "/usr/lib64/python3.4/site-packages/mypy/checkexpr.py", line 257, in check_call messages=arg_messages) File "/usr/lib64/python3.4/site-packages/mypy/checkexpr.py", line 666, in overload_call_target typ) File "/usr/lib64/python3.4/site-packages/mypy/checkexpr.py", line 742, in erased_signature_similarity None, check_arg=check_arg) File "/usr/lib64/python3.4/site-packages/mypy/checkexpr.py", line 614, in check_argument_types messages.invalid_keyword_var_arg(arg_type, context) File "/usr/lib64/python3.4/site-packages/mypy/messages.py", line 687, in invalid_keyword_var_arg context) File "/usr/lib64/python3.4/site-packages/mypy/messages.py", line 147, in fail self.report(msg, context, 'error', file=file) File "/usr/lib64/python3.4/site-packages/mypy/messages.py", line 143, in report self.errors.report(context.get_line(), msg.strip(), severity=severity, file=file) AttributeError: 'NoneType' object has no attribute 'get_line'
AttributeError
def infer_arg_types_in_context( self, callee: CallableType, args: List[Node] ) -> List[Type]: """Infer argument expression types using a callable type as context. For example, if callee argument 2 has type List[int], infer the argument expression with List[int] type context. """ # TODO Always called with callee as None, i.e. empty context. res = [] # type: List[Type] fixed = len(args) if callee: fixed = min(fixed, callee.max_fixed_args()) arg_type = None # type: Type ctx = None # type: Type for i, arg in enumerate(args): if i < fixed: if callee and i < len(callee.arg_types): ctx = callee.arg_types[i] arg_type = self.accept(arg, ctx) else: if callee and callee.is_var_arg: arg_type = self.accept(arg, callee.arg_types[-1]) else: arg_type = self.accept(arg) if has_erased_component(arg_type): res.append(NoneTyp()) else: res.append(arg_type) return res
def infer_arg_types_in_context( self, callee: CallableType, args: List[Node] ) -> List[Type]: """Infer argument expression types using a callable type as context. For example, if callee argument 2 has type List[int], infer the argument expression with List[int] type context. """ # TODO Always called with callee as None, i.e. empty context. res = [] # type: List[Type] fixed = len(args) if callee: fixed = min(fixed, callee.max_fixed_args()) arg_type = None # type: Type ctx = None # type: Type for i, arg in enumerate(args): if i < fixed: if callee and i < len(callee.arg_types): ctx = callee.arg_types[i] arg_type = self.accept(arg, ctx) else: if callee and callee.is_var_arg: arg_type = self.accept(arg, callee.arg_types[-1]) else: arg_type = self.accept(arg) if isinstance(arg_type, ErasedType): res.append(NoneTyp()) else: res.append(arg_type) return res
https://github.com/python/mypy/issues/1572
Traceback (most recent call last): File "/nix/store/czly6jrafckfvwm9mjc6wvandc2ddwi9-python3.5-mypy-lang-0.4.1/bin/.mypy-wrapped", line 7, in <module> main(__file__) File "/nix/store/czly6jrafckfvwm9mjc6wvandc2ddwi9-python3.5-mypy-lang-0.4.1/lib/python3.5/site-packages/mypy/main.py", line 54, in main res = type_check_only(sources, bin_dir, options) File "/nix/store/czly6jrafckfvwm9mjc6wvandc2ddwi9-python3.5-mypy-lang-0.4.1/lib/python3.5/site-packages/mypy/main.py", line 102, in type_check_only python_path=options.python_path) File "/nix/store/czly6jrafckfvwm9mjc6wvandc2ddwi9-python3.5-mypy-lang-0.4.1/lib/python3.5/site-packages/mypy/build.py", line 209, in build dispatch(sources, manager) File "/nix/store/czly6jrafckfvwm9mjc6wvandc2ddwi9-python3.5-mypy-lang-0.4.1/lib/python3.5/site-packages/mypy/build.py", line 1255, in dispatch process_graph(graph, manager) File "/nix/store/czly6jrafckfvwm9mjc6wvandc2ddwi9-python3.5-mypy-lang-0.4.1/lib/python3.5/site-packages/mypy/build.py", line 1386, in process_graph process_stale_scc(graph, scc) File "/nix/store/czly6jrafckfvwm9mjc6wvandc2ddwi9-python3.5-mypy-lang-0.4.1/lib/python3.5/site-packages/mypy/build.py", line 1416, in process_stale_scc graph[id].type_check() File "/nix/store/czly6jrafckfvwm9mjc6wvandc2ddwi9-python3.5-mypy-lang-0.4.1/lib/python3.5/site-packages/mypy/build.py", line 1235, in type_check manager.type_checker.visit_file(self.tree, self.xpath) File "/nix/store/czly6jrafckfvwm9mjc6wvandc2ddwi9-python3.5-mypy-lang-0.4.1/lib/python3.5/site-packages/mypy/checker.py", line 419, in visit_file self.accept(d) File "/nix/store/czly6jrafckfvwm9mjc6wvandc2ddwi9-python3.5-mypy-lang-0.4.1/lib/python3.5/site-packages/mypy/checker.py", line 460, in accept typ = node.accept(self) File "/nix/store/czly6jrafckfvwm9mjc6wvandc2ddwi9-python3.5-mypy-lang-0.4.1/lib/python3.5/site-packages/mypy/nodes.py", line 462, in accept return visitor.visit_func_def(self) File "/nix/store/czly6jrafckfvwm9mjc6wvandc2ddwi9-python3.5-mypy-lang-0.4.1/lib/python3.5/site-packages/mypy/checker.py", line 573, in visit_func_def self.check_func_item(defn, name=defn.name()) File "/nix/store/czly6jrafckfvwm9mjc6wvandc2ddwi9-python3.5-mypy-lang-0.4.1/lib/python3.5/site-packages/mypy/checker.py", line 631, in check_func_item self.check_func_def(defn, typ, name) File "/nix/store/czly6jrafckfvwm9mjc6wvandc2ddwi9-python3.5-mypy-lang-0.4.1/lib/python3.5/site-packages/mypy/checker.py", line 739, in check_func_def self.accept_in_frame(item.body) File "/nix/store/czly6jrafckfvwm9mjc6wvandc2ddwi9-python3.5-mypy-lang-0.4.1/lib/python3.5/site-packages/mypy/checker.py", line 475, in accept_in_frame answer = self.accept(node, type_context) File "/nix/store/czly6jrafckfvwm9mjc6wvandc2ddwi9-python3.5-mypy-lang-0.4.1/lib/python3.5/site-packages/mypy/checker.py", line 460, in accept typ = node.accept(self) File "/nix/store/czly6jrafckfvwm9mjc6wvandc2ddwi9-python3.5-mypy-lang-0.4.1/lib/python3.5/site-packages/mypy/nodes.py", line 715, in accept return visitor.visit_block(self) File "/nix/store/czly6jrafckfvwm9mjc6wvandc2ddwi9-python3.5-mypy-lang-0.4.1/lib/python3.5/site-packages/mypy/checker.py", line 1132, in visit_block self.accept(s) File "/nix/store/czly6jrafckfvwm9mjc6wvandc2ddwi9-python3.5-mypy-lang-0.4.1/lib/python3.5/site-packages/mypy/checker.py", line 460, in accept typ = node.accept(self) File "/nix/store/czly6jrafckfvwm9mjc6wvandc2ddwi9-python3.5-mypy-lang-0.4.1/lib/python3.5/site-packages/mypy/nodes.py", line 753, in accept return visitor.visit_assignment_stmt(self) File "/nix/store/czly6jrafckfvwm9mjc6wvandc2ddwi9-python3.5-mypy-lang-0.4.1/lib/python3.5/site-packages/mypy/checker.py", line 1141, in visit_assignment_stmt self.check_assignment(s.lvalues[-1], s.rvalue, s.type is None) File "/nix/store/czly6jrafckfvwm9mjc6wvandc2ddwi9-python3.5-mypy-lang-0.4.1/lib/python3.5/site-packages/mypy/checker.py", line 1192, in check_assignment rvalue) File "/nix/store/czly6jrafckfvwm9mjc6wvandc2ddwi9-python3.5-mypy-lang-0.4.1/lib/python3.5/site-packages/mypy/checker.py", line 1424, in infer_variable_type elif not is_valid_inferred_type(init_type): File "/nix/store/czly6jrafckfvwm9mjc6wvandc2ddwi9-python3.5-mypy-lang-0.4.1/lib/python3.5/site-packages/mypy/checker.py", line 2549, in is_valid_inferred_type if not is_valid_inferred_type(item): File "/nix/store/czly6jrafckfvwm9mjc6wvandc2ddwi9-python3.5-mypy-lang-0.4.1/lib/python3.5/site-packages/mypy/checker.py", line 2541, in is_valid_inferred_type if is_same_type(typ, NoneTyp()): File "/nix/store/czly6jrafckfvwm9mjc6wvandc2ddwi9-python3.5-mypy-lang-0.4.1/lib/python3.5/site-packages/mypy/sametypes.py", line 27, in is_same_type return left.accept(SameTypeVisitor(right)) File "/nix/store/czly6jrafckfvwm9mjc6wvandc2ddwi9-python3.5-mypy-lang-0.4.1/lib/python3.5/site-packages/mypy/types.py", line 244, in accept return visitor.visit_erased_type(self) File "/nix/store/czly6jrafckfvwm9mjc6wvandc2ddwi9-python3.5-mypy-lang-0.4.1/lib/python3.5/site-packages/mypy/sametypes.py", line 74, in visit_erased_type raise RuntimeError() RuntimeError: *** INTERNAL ERROR ***
RuntimeError
def infer_function_type_arguments_pass2( self, callee_type: CallableType, args: List[Node], arg_kinds: List[int], formal_to_actual: List[List[int]], inferred_args: List[Type], context: Context, ) -> Tuple[CallableType, List[Type]]: """Perform second pass of generic function type argument inference. The second pass is needed for arguments with types such as Callable[[T], S], where both T and S are type variables, when the actual argument is a lambda with inferred types. The idea is to infer the type variable T in the first pass (based on the types of other arguments). This lets us infer the argument and return type of the lambda expression and thus also the type variable S in this second pass. Return (the callee with type vars applied, inferred actual arg types). """ # None or erased types in inferred types mean that there was not enough # information to infer the argument. Replace them with None values so # that they are not applied yet below. for i, arg in enumerate(inferred_args): if isinstance(arg, NoneTyp) or has_erased_component(arg): inferred_args[i] = None callee_type = cast( CallableType, self.apply_generic_arguments(callee_type, inferred_args, context) ) arg_types = self.infer_arg_types_in_context2( callee_type, args, arg_kinds, formal_to_actual ) inferred_args = infer_function_type_arguments( callee_type, arg_types, arg_kinds, formal_to_actual ) return callee_type, inferred_args
def infer_function_type_arguments_pass2( self, callee_type: CallableType, args: List[Node], arg_kinds: List[int], formal_to_actual: List[List[int]], inferred_args: List[Type], context: Context, ) -> Tuple[CallableType, List[Type]]: """Perform second pass of generic function type argument inference. The second pass is needed for arguments with types such as Callable[[T], S], where both T and S are type variables, when the actual argument is a lambda with inferred types. The idea is to infer the type variable T in the first pass (based on the types of other arguments). This lets us infer the argument and return type of the lambda expression and thus also the type variable S in this second pass. Return (the callee with type vars applied, inferred actual arg types). """ # None or erased types in inferred types mean that there was not enough # information to infer the argument. Replace them with None values so # that they are not applied yet below. for i, arg in enumerate(inferred_args): if isinstance(arg, NoneTyp) or isinstance(arg, ErasedType): inferred_args[i] = None callee_type = cast( CallableType, self.apply_generic_arguments(callee_type, inferred_args, context) ) arg_types = self.infer_arg_types_in_context2( callee_type, args, arg_kinds, formal_to_actual ) inferred_args = infer_function_type_arguments( callee_type, arg_types, arg_kinds, formal_to_actual ) return callee_type, inferred_args
https://github.com/python/mypy/issues/1572
Traceback (most recent call last): File "/nix/store/czly6jrafckfvwm9mjc6wvandc2ddwi9-python3.5-mypy-lang-0.4.1/bin/.mypy-wrapped", line 7, in <module> main(__file__) File "/nix/store/czly6jrafckfvwm9mjc6wvandc2ddwi9-python3.5-mypy-lang-0.4.1/lib/python3.5/site-packages/mypy/main.py", line 54, in main res = type_check_only(sources, bin_dir, options) File "/nix/store/czly6jrafckfvwm9mjc6wvandc2ddwi9-python3.5-mypy-lang-0.4.1/lib/python3.5/site-packages/mypy/main.py", line 102, in type_check_only python_path=options.python_path) File "/nix/store/czly6jrafckfvwm9mjc6wvandc2ddwi9-python3.5-mypy-lang-0.4.1/lib/python3.5/site-packages/mypy/build.py", line 209, in build dispatch(sources, manager) File "/nix/store/czly6jrafckfvwm9mjc6wvandc2ddwi9-python3.5-mypy-lang-0.4.1/lib/python3.5/site-packages/mypy/build.py", line 1255, in dispatch process_graph(graph, manager) File "/nix/store/czly6jrafckfvwm9mjc6wvandc2ddwi9-python3.5-mypy-lang-0.4.1/lib/python3.5/site-packages/mypy/build.py", line 1386, in process_graph process_stale_scc(graph, scc) File "/nix/store/czly6jrafckfvwm9mjc6wvandc2ddwi9-python3.5-mypy-lang-0.4.1/lib/python3.5/site-packages/mypy/build.py", line 1416, in process_stale_scc graph[id].type_check() File "/nix/store/czly6jrafckfvwm9mjc6wvandc2ddwi9-python3.5-mypy-lang-0.4.1/lib/python3.5/site-packages/mypy/build.py", line 1235, in type_check manager.type_checker.visit_file(self.tree, self.xpath) File "/nix/store/czly6jrafckfvwm9mjc6wvandc2ddwi9-python3.5-mypy-lang-0.4.1/lib/python3.5/site-packages/mypy/checker.py", line 419, in visit_file self.accept(d) File "/nix/store/czly6jrafckfvwm9mjc6wvandc2ddwi9-python3.5-mypy-lang-0.4.1/lib/python3.5/site-packages/mypy/checker.py", line 460, in accept typ = node.accept(self) File "/nix/store/czly6jrafckfvwm9mjc6wvandc2ddwi9-python3.5-mypy-lang-0.4.1/lib/python3.5/site-packages/mypy/nodes.py", line 462, in accept return visitor.visit_func_def(self) File "/nix/store/czly6jrafckfvwm9mjc6wvandc2ddwi9-python3.5-mypy-lang-0.4.1/lib/python3.5/site-packages/mypy/checker.py", line 573, in visit_func_def self.check_func_item(defn, name=defn.name()) File "/nix/store/czly6jrafckfvwm9mjc6wvandc2ddwi9-python3.5-mypy-lang-0.4.1/lib/python3.5/site-packages/mypy/checker.py", line 631, in check_func_item self.check_func_def(defn, typ, name) File "/nix/store/czly6jrafckfvwm9mjc6wvandc2ddwi9-python3.5-mypy-lang-0.4.1/lib/python3.5/site-packages/mypy/checker.py", line 739, in check_func_def self.accept_in_frame(item.body) File "/nix/store/czly6jrafckfvwm9mjc6wvandc2ddwi9-python3.5-mypy-lang-0.4.1/lib/python3.5/site-packages/mypy/checker.py", line 475, in accept_in_frame answer = self.accept(node, type_context) File "/nix/store/czly6jrafckfvwm9mjc6wvandc2ddwi9-python3.5-mypy-lang-0.4.1/lib/python3.5/site-packages/mypy/checker.py", line 460, in accept typ = node.accept(self) File "/nix/store/czly6jrafckfvwm9mjc6wvandc2ddwi9-python3.5-mypy-lang-0.4.1/lib/python3.5/site-packages/mypy/nodes.py", line 715, in accept return visitor.visit_block(self) File "/nix/store/czly6jrafckfvwm9mjc6wvandc2ddwi9-python3.5-mypy-lang-0.4.1/lib/python3.5/site-packages/mypy/checker.py", line 1132, in visit_block self.accept(s) File "/nix/store/czly6jrafckfvwm9mjc6wvandc2ddwi9-python3.5-mypy-lang-0.4.1/lib/python3.5/site-packages/mypy/checker.py", line 460, in accept typ = node.accept(self) File "/nix/store/czly6jrafckfvwm9mjc6wvandc2ddwi9-python3.5-mypy-lang-0.4.1/lib/python3.5/site-packages/mypy/nodes.py", line 753, in accept return visitor.visit_assignment_stmt(self) File "/nix/store/czly6jrafckfvwm9mjc6wvandc2ddwi9-python3.5-mypy-lang-0.4.1/lib/python3.5/site-packages/mypy/checker.py", line 1141, in visit_assignment_stmt self.check_assignment(s.lvalues[-1], s.rvalue, s.type is None) File "/nix/store/czly6jrafckfvwm9mjc6wvandc2ddwi9-python3.5-mypy-lang-0.4.1/lib/python3.5/site-packages/mypy/checker.py", line 1192, in check_assignment rvalue) File "/nix/store/czly6jrafckfvwm9mjc6wvandc2ddwi9-python3.5-mypy-lang-0.4.1/lib/python3.5/site-packages/mypy/checker.py", line 1424, in infer_variable_type elif not is_valid_inferred_type(init_type): File "/nix/store/czly6jrafckfvwm9mjc6wvandc2ddwi9-python3.5-mypy-lang-0.4.1/lib/python3.5/site-packages/mypy/checker.py", line 2549, in is_valid_inferred_type if not is_valid_inferred_type(item): File "/nix/store/czly6jrafckfvwm9mjc6wvandc2ddwi9-python3.5-mypy-lang-0.4.1/lib/python3.5/site-packages/mypy/checker.py", line 2541, in is_valid_inferred_type if is_same_type(typ, NoneTyp()): File "/nix/store/czly6jrafckfvwm9mjc6wvandc2ddwi9-python3.5-mypy-lang-0.4.1/lib/python3.5/site-packages/mypy/sametypes.py", line 27, in is_same_type return left.accept(SameTypeVisitor(right)) File "/nix/store/czly6jrafckfvwm9mjc6wvandc2ddwi9-python3.5-mypy-lang-0.4.1/lib/python3.5/site-packages/mypy/types.py", line 244, in accept return visitor.visit_erased_type(self) File "/nix/store/czly6jrafckfvwm9mjc6wvandc2ddwi9-python3.5-mypy-lang-0.4.1/lib/python3.5/site-packages/mypy/sametypes.py", line 74, in visit_erased_type raise RuntimeError() RuntimeError: *** INTERNAL ERROR ***
RuntimeError
def apply_inferred_arguments( self, callee_type: CallableType, inferred_args: List[Type], context: Context ) -> CallableType: """Apply inferred values of type arguments to a generic function. Inferred_args contains the values of function type arguments. """ # Report error if some of the variables could not be solved. In that # case assume that all variables have type Any to avoid extra # bogus error messages. for i, inferred_type in enumerate(inferred_args): if not inferred_type or has_erased_component(inferred_type): # Could not infer a non-trivial type for a type variable. self.msg.could_not_infer_type_arguments(callee_type, i + 1, context) inferred_args = [AnyType()] * len(inferred_args) # Apply the inferred types to the function type. In this case the # return type must be CallableType, since we give the right number of type # arguments. return cast( CallableType, self.apply_generic_arguments(callee_type, inferred_args, context) )
def apply_inferred_arguments( self, callee_type: CallableType, inferred_args: List[Type], context: Context ) -> CallableType: """Apply inferred values of type arguments to a generic function. Inferred_args contains the values of function type arguments. """ # Report error if some of the variables could not be solved. In that # case assume that all variables have type Any to avoid extra # bogus error messages. for i, inferred_type in enumerate(inferred_args): if not inferred_type: # Could not infer a non-trivial type for a type variable. self.msg.could_not_infer_type_arguments(callee_type, i + 1, context) inferred_args = [AnyType()] * len(inferred_args) # Apply the inferred types to the function type. In this case the # return type must be CallableType, since we give the right number of type # arguments. return cast( CallableType, self.apply_generic_arguments(callee_type, inferred_args, context) )
https://github.com/python/mypy/issues/1572
Traceback (most recent call last): File "/nix/store/czly6jrafckfvwm9mjc6wvandc2ddwi9-python3.5-mypy-lang-0.4.1/bin/.mypy-wrapped", line 7, in <module> main(__file__) File "/nix/store/czly6jrafckfvwm9mjc6wvandc2ddwi9-python3.5-mypy-lang-0.4.1/lib/python3.5/site-packages/mypy/main.py", line 54, in main res = type_check_only(sources, bin_dir, options) File "/nix/store/czly6jrafckfvwm9mjc6wvandc2ddwi9-python3.5-mypy-lang-0.4.1/lib/python3.5/site-packages/mypy/main.py", line 102, in type_check_only python_path=options.python_path) File "/nix/store/czly6jrafckfvwm9mjc6wvandc2ddwi9-python3.5-mypy-lang-0.4.1/lib/python3.5/site-packages/mypy/build.py", line 209, in build dispatch(sources, manager) File "/nix/store/czly6jrafckfvwm9mjc6wvandc2ddwi9-python3.5-mypy-lang-0.4.1/lib/python3.5/site-packages/mypy/build.py", line 1255, in dispatch process_graph(graph, manager) File "/nix/store/czly6jrafckfvwm9mjc6wvandc2ddwi9-python3.5-mypy-lang-0.4.1/lib/python3.5/site-packages/mypy/build.py", line 1386, in process_graph process_stale_scc(graph, scc) File "/nix/store/czly6jrafckfvwm9mjc6wvandc2ddwi9-python3.5-mypy-lang-0.4.1/lib/python3.5/site-packages/mypy/build.py", line 1416, in process_stale_scc graph[id].type_check() File "/nix/store/czly6jrafckfvwm9mjc6wvandc2ddwi9-python3.5-mypy-lang-0.4.1/lib/python3.5/site-packages/mypy/build.py", line 1235, in type_check manager.type_checker.visit_file(self.tree, self.xpath) File "/nix/store/czly6jrafckfvwm9mjc6wvandc2ddwi9-python3.5-mypy-lang-0.4.1/lib/python3.5/site-packages/mypy/checker.py", line 419, in visit_file self.accept(d) File "/nix/store/czly6jrafckfvwm9mjc6wvandc2ddwi9-python3.5-mypy-lang-0.4.1/lib/python3.5/site-packages/mypy/checker.py", line 460, in accept typ = node.accept(self) File "/nix/store/czly6jrafckfvwm9mjc6wvandc2ddwi9-python3.5-mypy-lang-0.4.1/lib/python3.5/site-packages/mypy/nodes.py", line 462, in accept return visitor.visit_func_def(self) File "/nix/store/czly6jrafckfvwm9mjc6wvandc2ddwi9-python3.5-mypy-lang-0.4.1/lib/python3.5/site-packages/mypy/checker.py", line 573, in visit_func_def self.check_func_item(defn, name=defn.name()) File "/nix/store/czly6jrafckfvwm9mjc6wvandc2ddwi9-python3.5-mypy-lang-0.4.1/lib/python3.5/site-packages/mypy/checker.py", line 631, in check_func_item self.check_func_def(defn, typ, name) File "/nix/store/czly6jrafckfvwm9mjc6wvandc2ddwi9-python3.5-mypy-lang-0.4.1/lib/python3.5/site-packages/mypy/checker.py", line 739, in check_func_def self.accept_in_frame(item.body) File "/nix/store/czly6jrafckfvwm9mjc6wvandc2ddwi9-python3.5-mypy-lang-0.4.1/lib/python3.5/site-packages/mypy/checker.py", line 475, in accept_in_frame answer = self.accept(node, type_context) File "/nix/store/czly6jrafckfvwm9mjc6wvandc2ddwi9-python3.5-mypy-lang-0.4.1/lib/python3.5/site-packages/mypy/checker.py", line 460, in accept typ = node.accept(self) File "/nix/store/czly6jrafckfvwm9mjc6wvandc2ddwi9-python3.5-mypy-lang-0.4.1/lib/python3.5/site-packages/mypy/nodes.py", line 715, in accept return visitor.visit_block(self) File "/nix/store/czly6jrafckfvwm9mjc6wvandc2ddwi9-python3.5-mypy-lang-0.4.1/lib/python3.5/site-packages/mypy/checker.py", line 1132, in visit_block self.accept(s) File "/nix/store/czly6jrafckfvwm9mjc6wvandc2ddwi9-python3.5-mypy-lang-0.4.1/lib/python3.5/site-packages/mypy/checker.py", line 460, in accept typ = node.accept(self) File "/nix/store/czly6jrafckfvwm9mjc6wvandc2ddwi9-python3.5-mypy-lang-0.4.1/lib/python3.5/site-packages/mypy/nodes.py", line 753, in accept return visitor.visit_assignment_stmt(self) File "/nix/store/czly6jrafckfvwm9mjc6wvandc2ddwi9-python3.5-mypy-lang-0.4.1/lib/python3.5/site-packages/mypy/checker.py", line 1141, in visit_assignment_stmt self.check_assignment(s.lvalues[-1], s.rvalue, s.type is None) File "/nix/store/czly6jrafckfvwm9mjc6wvandc2ddwi9-python3.5-mypy-lang-0.4.1/lib/python3.5/site-packages/mypy/checker.py", line 1192, in check_assignment rvalue) File "/nix/store/czly6jrafckfvwm9mjc6wvandc2ddwi9-python3.5-mypy-lang-0.4.1/lib/python3.5/site-packages/mypy/checker.py", line 1424, in infer_variable_type elif not is_valid_inferred_type(init_type): File "/nix/store/czly6jrafckfvwm9mjc6wvandc2ddwi9-python3.5-mypy-lang-0.4.1/lib/python3.5/site-packages/mypy/checker.py", line 2549, in is_valid_inferred_type if not is_valid_inferred_type(item): File "/nix/store/czly6jrafckfvwm9mjc6wvandc2ddwi9-python3.5-mypy-lang-0.4.1/lib/python3.5/site-packages/mypy/checker.py", line 2541, in is_valid_inferred_type if is_same_type(typ, NoneTyp()): File "/nix/store/czly6jrafckfvwm9mjc6wvandc2ddwi9-python3.5-mypy-lang-0.4.1/lib/python3.5/site-packages/mypy/sametypes.py", line 27, in is_same_type return left.accept(SameTypeVisitor(right)) File "/nix/store/czly6jrafckfvwm9mjc6wvandc2ddwi9-python3.5-mypy-lang-0.4.1/lib/python3.5/site-packages/mypy/types.py", line 244, in accept return visitor.visit_erased_type(self) File "/nix/store/czly6jrafckfvwm9mjc6wvandc2ddwi9-python3.5-mypy-lang-0.4.1/lib/python3.5/site-packages/mypy/sametypes.py", line 74, in visit_erased_type raise RuntimeError() RuntimeError: *** INTERNAL ERROR ***
RuntimeError
def visit_for_stmt(self, s: ForStmt) -> None: self.analyze_lvalue(s.index) s.body.accept(self) if s.else_body: s.else_body.accept(self)
def visit_for_stmt(self, s: ForStmt) -> None: self.analyze_lvalue(s.index) s.body.accept(self)
https://github.com/python/mypy/issues/1565
Traceback (most recent call last): File "/usr/bin/mypy", line 6, in <module> main(__file__) File "/usr/lib/python3.5/site-packages/mypy/main.py", line 54, in main res = type_check_only(sources, bin_dir, options) File "/usr/lib/python3.5/site-packages/mypy/main.py", line 102, in type_check_only python_path=options.python_path) File "/usr/lib/python3.5/site-packages/mypy/build.py", line 209, in build dispatch(sources, manager) File "/usr/lib/python3.5/site-packages/mypy/build.py", line 1255, in dispatch process_graph(graph, manager) File "/usr/lib/python3.5/site-packages/mypy/build.py", line 1386, in process_graph process_stale_scc(graph, scc) File "/usr/lib/python3.5/site-packages/mypy/build.py", line 1412, in process_stale_scc graph[id].semantic_analysis() File "/usr/lib/python3.5/site-packages/mypy/build.py", line 1222, in semantic_analysis self.manager.semantic_analyzer.visit_file(self.tree, self.xpath) File "/usr/lib/python3.5/site-packages/mypy/semanal.py", line 241, in visit_file self.accept(d) File "/usr/lib/python3.5/site-packages/mypy/semanal.py", line 2233, in accept node.accept(self) File "/usr/lib/python3.5/site-packages/mypy/nodes.py", line 783, in accept return visitor.visit_while_stmt(self) File "/usr/lib/python3.5/site-packages/mypy/semanal.py", line 1620, in visit_while_stmt s.body.accept(self) File "/usr/lib/python3.5/site-packages/mypy/nodes.py", line 715, in accept return visitor.visit_block(self) File "/usr/lib/python3.5/site-packages/mypy/semanal.py", line 1003, in visit_block self.accept(s) File "/usr/lib/python3.5/site-packages/mypy/semanal.py", line 2233, in accept node.accept(self) File "/usr/lib/python3.5/site-packages/mypy/nodes.py", line 462, in accept return visitor.visit_func_def(self) File "/usr/lib/python3.5/site-packages/mypy/semanal.py", line 295, in visit_func_def if isinstance(symbol.node, FuncDef) and symbol.node != defn: AttributeError: 'NoneType' object has no attribute 'node' *** INTERNAL ERROR ***
AttributeError
def visit_while_stmt(self, s: WhileStmt) -> None: s.body.accept(self) if s.else_body: s.else_body.accept(self)
def visit_while_stmt(self, s: WhileStmt) -> None: s.expr.accept(self) self.loop_depth += 1 s.body.accept(self) self.loop_depth -= 1 self.visit_block_maybe(s.else_body)
https://github.com/python/mypy/issues/1565
Traceback (most recent call last): File "/usr/bin/mypy", line 6, in <module> main(__file__) File "/usr/lib/python3.5/site-packages/mypy/main.py", line 54, in main res = type_check_only(sources, bin_dir, options) File "/usr/lib/python3.5/site-packages/mypy/main.py", line 102, in type_check_only python_path=options.python_path) File "/usr/lib/python3.5/site-packages/mypy/build.py", line 209, in build dispatch(sources, manager) File "/usr/lib/python3.5/site-packages/mypy/build.py", line 1255, in dispatch process_graph(graph, manager) File "/usr/lib/python3.5/site-packages/mypy/build.py", line 1386, in process_graph process_stale_scc(graph, scc) File "/usr/lib/python3.5/site-packages/mypy/build.py", line 1412, in process_stale_scc graph[id].semantic_analysis() File "/usr/lib/python3.5/site-packages/mypy/build.py", line 1222, in semantic_analysis self.manager.semantic_analyzer.visit_file(self.tree, self.xpath) File "/usr/lib/python3.5/site-packages/mypy/semanal.py", line 241, in visit_file self.accept(d) File "/usr/lib/python3.5/site-packages/mypy/semanal.py", line 2233, in accept node.accept(self) File "/usr/lib/python3.5/site-packages/mypy/nodes.py", line 783, in accept return visitor.visit_while_stmt(self) File "/usr/lib/python3.5/site-packages/mypy/semanal.py", line 1620, in visit_while_stmt s.body.accept(self) File "/usr/lib/python3.5/site-packages/mypy/nodes.py", line 715, in accept return visitor.visit_block(self) File "/usr/lib/python3.5/site-packages/mypy/semanal.py", line 1003, in visit_block self.accept(s) File "/usr/lib/python3.5/site-packages/mypy/semanal.py", line 2233, in accept node.accept(self) File "/usr/lib/python3.5/site-packages/mypy/nodes.py", line 462, in accept return visitor.visit_func_def(self) File "/usr/lib/python3.5/site-packages/mypy/semanal.py", line 295, in visit_func_def if isinstance(symbol.node, FuncDef) and symbol.node != defn: AttributeError: 'NoneType' object has no attribute 'node' *** INTERNAL ERROR ***
AttributeError
def visit_func_expr(self, e: FuncExpr) -> Type: """Type check lambda expression.""" inferred_type = self.infer_lambda_type_using_context(e) if not inferred_type: # No useful type context. ret_type = e.expr().accept(self.chk) if not e.arguments: # Form 'lambda: e'; just use the inferred return type. return CallableType( [], [], [], ret_type, self.named_type("builtins.function") ) else: # TODO: Consider reporting an error. However, this is fine if # we are just doing the first pass in contextual type # inference. return AnyType() else: # Type context available. self.chk.check_func_item(e, type_override=inferred_type) if e.expr() not in self.chk.type_map: self.accept(e.expr()) ret_type = self.chk.type_map[e.expr()] return replace_callable_return_type(inferred_type, ret_type)
def visit_func_expr(self, e: FuncExpr) -> Type: """Type check lambda expression.""" inferred_type = self.infer_lambda_type_using_context(e) if not inferred_type: # No useful type context. ret_type = e.expr().accept(self.chk) if not e.arguments: # Form 'lambda: e'; just use the inferred return type. return CallableType( [], [], [], ret_type, self.named_type("builtins.function") ) else: # TODO: Consider reporting an error. However, this is fine if # we are just doing the first pass in contextual type # inference. return AnyType() else: # Type context available. self.chk.check_func_item(e, type_override=inferred_type) ret_type = self.chk.type_map[e.expr()] return replace_callable_return_type(inferred_type, ret_type)
https://github.com/python/mypy/issues/1421
Traceback (most recent call last): File "/Users/guido/v3/bin/mypy", line 6, in <module> main(__file__) File "/Users/guido/v3/lib/python3.5/site-packages/mypy/main.py", line 52, in main res = type_check_only(sources, bin_dir, options) File "/Users/guido/v3/lib/python3.5/site-packages/mypy/main.py", line 100, in type_check_only python_path=options.python_path) File "/Users/guido/v3/lib/python3.5/site-packages/mypy/build.py", line 208, in build dispatch(sources, manager) File "/Users/guido/v3/lib/python3.5/site-packages/mypy/build.py", line 1251, in dispatch process_graph(graph, manager) File "/Users/guido/v3/lib/python3.5/site-packages/mypy/build.py", line 1382, in process_graph process_stale_scc(graph, scc) File "/Users/guido/v3/lib/python3.5/site-packages/mypy/build.py", line 1412, in process_stale_scc graph[id].type_check() File "/Users/guido/v3/lib/python3.5/site-packages/mypy/build.py", line 1231, in type_check manager.type_checker.visit_file(self.tree, self.xpath) File "/Users/guido/v3/lib/python3.5/site-packages/mypy/checker.py", line 419, in visit_file self.accept(d) File "/Users/guido/v3/lib/python3.5/site-packages/mypy/checker.py", line 460, in accept typ = node.accept(self) File "/Users/guido/v3/lib/python3.5/site-packages/mypy/nodes.py", line 462, in accept return visitor.visit_func_def(self) File "/Users/guido/v3/lib/python3.5/site-packages/mypy/checker.py", line 573, in visit_func_def self.check_func_item(defn, name=defn.name()) File "/Users/guido/v3/lib/python3.5/site-packages/mypy/checker.py", line 631, in check_func_item self.check_func_def(defn, typ, name) File "/Users/guido/v3/lib/python3.5/site-packages/mypy/checker.py", line 739, in check_func_def self.accept_in_frame(item.body) File "/Users/guido/v3/lib/python3.5/site-packages/mypy/checker.py", line 475, in accept_in_frame answer = self.accept(node, type_context) File "/Users/guido/v3/lib/python3.5/site-packages/mypy/checker.py", line 460, in accept typ = node.accept(self) File "/Users/guido/v3/lib/python3.5/site-packages/mypy/nodes.py", line 715, in accept return visitor.visit_block(self) File "/Users/guido/v3/lib/python3.5/site-packages/mypy/checker.py", line 1133, in visit_block self.accept(s) File "/Users/guido/v3/lib/python3.5/site-packages/mypy/checker.py", line 460, in accept typ = node.accept(self) File "/Users/guido/v3/lib/python3.5/site-packages/mypy/nodes.py", line 812, in accept return visitor.visit_return_stmt(self) File "/Users/guido/v3/lib/python3.5/site-packages/mypy/checker.py", line 1565, in visit_return_stmt typ = self.accept(s.expr, return_type) File "/Users/guido/v3/lib/python3.5/site-packages/mypy/checker.py", line 460, in accept typ = node.accept(self) File "/Users/guido/v3/lib/python3.5/site-packages/mypy/nodes.py", line 1174, in accept return visitor.visit_call_expr(self) File "/Users/guido/v3/lib/python3.5/site-packages/mypy/checker.py", line 1974, in visit_call_expr return self.expr_checker.visit_call_expr(e) File "/Users/guido/v3/lib/python3.5/site-packages/mypy/checkexpr.py", line 145, in visit_call_expr return self.check_call_expr_with_callee_type(callee_type, e) File "/Users/guido/v3/lib/python3.5/site-packages/mypy/checkexpr.py", line 196, in check_call_expr_with_callee_type e.arg_names, callable_node=e.callee)[0] File "/Users/guido/v3/lib/python3.5/site-packages/mypy/checkexpr.py", line 239, in check_call callee, args, arg_kinds, formal_to_actual) File "/Users/guido/v3/lib/python3.5/site-packages/mypy/checkexpr.py", line 334, in infer_arg_types_in_context2 res[ai] = self.accept(args[ai], callee.arg_types[i]) File "/Users/guido/v3/lib/python3.5/site-packages/mypy/checkexpr.py", line 1459, in accept return self.chk.accept(node, context) File "/Users/guido/v3/lib/python3.5/site-packages/mypy/checker.py", line 460, in accept typ = node.accept(self) File "/Users/guido/v3/lib/python3.5/site-packages/mypy/nodes.py", line 1396, in accept return visitor.visit_func_expr(self) File "/Users/guido/v3/lib/python3.5/site-packages/mypy/checker.py", line 2099, in visit_func_expr return self.expr_checker.visit_func_expr(e) File "/Users/guido/v3/lib/python3.5/site-packages/mypy/checkexpr.py", line 1275, in visit_func_expr ret_type = self.chk.type_map[e.expr()] KeyError: <mypy.nodes.NameExpr object at 0x106139e48>
KeyError
def visit_assignment_stmt(self, s: AssignmentStmt) -> Type: """Type check an assignment statement. Handle all kinds of assignment statements (simple, indexed, multiple). """ self.check_assignment(s.lvalues[-1], s.rvalue, s.type is None) if len(s.lvalues) > 1: # Chained assignment (e.g. x = y = ...). # Make sure that rvalue type will not be reinferred. if s.rvalue not in self.type_map: self.accept(s.rvalue) rvalue = self.temp_node(self.type_map[s.rvalue], s) for lv in s.lvalues[:-1]: self.check_assignment(lv, rvalue, s.type is None)
def visit_assignment_stmt(self, s: AssignmentStmt) -> Type: """Type check an assignment statement. Handle all kinds of assignment statements (simple, indexed, multiple). """ self.check_assignment(s.lvalues[-1], s.rvalue, s.type is None) if len(s.lvalues) > 1: # Chained assignment (e.g. x = y = ...). # Make sure that rvalue type will not be reinferred. rvalue = self.temp_node(self.type_map[s.rvalue], s) for lv in s.lvalues[:-1]: self.check_assignment(lv, rvalue, s.type is None)
https://github.com/python/mypy/issues/974
Traceback (most recent call last): File "/Users/me/py-env/crf/bin/mypy", line 6, in <module> main(__file__) File "/Users/me/py-env/crf/lib/python3.5/site-packages/mypy/main.py", line 49, in main type_check_only(sources, bin_dir, options) File "/Users/me/py-env/crf/lib/python3.5/site-packages/mypy/main.py", line 92, in type_check_only python_path=options.python_path) File "/Users/me/py-env/crf/lib/python3.5/site-packages/mypy/build.py", line 196, in build result = manager.process(initial_states) File "/Users/me/py-env/crf/lib/python3.5/site-packages/mypy/build.py", line 378, in process next.process() File "/Users/me/py-env/crf/lib/python3.5/site-packages/mypy/build.py", line 832, in process self.type_checker().visit_file(self.tree, self.tree.path) File "/Users/me/py-env/crf/lib/python3.5/site-packages/mypy/checker.py", line 371, in visit_file self.accept(d) File "/Users/me/py-env/crf/lib/python3.5/site-packages/mypy/checker.py", line 378, in accept typ = node.accept(self) File "/Users/me/py-env/crf/lib/python3.5/site-packages/mypy/nodes.py", line 538, in accept return visitor.visit_assignment_stmt(self) File "/Users/me/py-env/crf/lib/python3.5/site-packages/mypy/checker.py", line 954, in visit_assignment_stmt rvalue = self.temp_node(self.type_map[s.rvalue], s) KeyError: <mypy.nodes.TupleExpr object at 0x1017950b8>
KeyError
def remove_imported_names_from_symtable(names: SymbolTable, module: str) -> None: """Remove all imported names from the symbol table of a module.""" removed = [] # type: List[str] for name, node in names.items(): if node.node is None: continue fullname = node.node.fullname() prefix = fullname[: fullname.rfind(".")] if prefix != module: removed.append(name) for name in removed: del names[name]
def remove_imported_names_from_symtable(names: SymbolTable, module: str) -> None: """Remove all imported names from the symbol table of a module.""" removed = [] # type: List[str] for name, node in names.items(): fullname = node.node.fullname() prefix = fullname[: fullname.rfind(".")] if prefix != module: removed.append(name) for name in removed: del names[name]
https://github.com/python/mypy/issues/1182
Traceback (most recent call last): File "/usr/local/bin/mypy", line 6, in <module> main(__file__) File "/usr/local/lib/python3.4/dist-packages/mypy/main.py", line 53, in main type_check_only(sources, bin_dir, options) File "/usr/local/lib/python3.4/dist-packages/mypy/main.py", line 96, in type_check_only python_path=options.python_path) File "/usr/local/lib/python3.4/dist-packages/mypy/build.py", line 203, in build result = manager.process(initial_states) File "/usr/local/lib/python3.4/dist-packages/mypy/build.py", line 386, in process next.process() File "/usr/local/lib/python3.4/dist-packages/mypy/build.py", line 846, in process main(__file__) File "/usr/local/lib/python3.4/dist-packages/mypy/main.py", line 53, in main type_check_only(sources, bin_dir, options) File "/usr/local/lib/python3.4/dist-packages/mypy/main.py", line 96, in type_check_only python_path=options.python_path) File "/usr/local/lib/python3.4/dist-packages/mypy/build.py", line 203, in build result = manager.process(initial_states) File "/usr/local/lib/python3.4/dist-packages/mypy/build.py", line 386, in process next.process() File "/usr/local/lib/python3.4/dist-packages/mypy/build.py", line 846, in process self.semantic_analyzer().visit_file(self.tree, self.tree.path) File "/usr/local/lib/python3.4/dist-packages/mypy/semanal.py", line 213, in visit_file remove_imported_names_from_symtable(self.globals, 'builtins') File "/usr/local/lib/python3.4/dist-packages/mypy/semanal.py", line 2445, in remove_imported_names_from_symtable fullname = node.node.fullname() AttributeError: 'NoneType' object has no attribute 'fullname'
AttributeError
def try_infer_partial_type_from_indexed_assignment( self, lvalue: IndexExpr, rvalue: Node ) -> None: # TODO: Should we share some of this with try_infer_partial_type? if isinstance(lvalue.base, RefExpr) and isinstance(lvalue.base.node, Var): var = cast(Var, lvalue.base.node) if var is not None and isinstance(var.type, PartialType): type_type = var.type.type if type_type is None: return # The partial type is None. partial_types = self.find_partial_types(var) if partial_types is None: return typename = type_type.fullname() if typename == "builtins.dict": # TODO: Don't infer things twice. key_type = self.accept(lvalue.index) value_type = self.accept(rvalue) if is_valid_inferred_type(key_type) and is_valid_inferred_type( value_type ): if not self.current_node_deferred: var.type = self.named_generic_type( "builtins.dict", [key_type, value_type] ) del partial_types[var]
def try_infer_partial_type_from_indexed_assignment( self, lvalue: IndexExpr, rvalue: Node ) -> None: # TODO: Should we share some of this with try_infer_partial_type? if isinstance(lvalue.base, RefExpr): var = cast(Var, lvalue.base.node) if var is not None and isinstance(var.type, PartialType): type_type = var.type.type if type_type is None: return # The partial type is None. partial_types = self.find_partial_types(var) if partial_types is None: return typename = type_type.fullname() if typename == "builtins.dict": # TODO: Don't infer things twice. key_type = self.accept(lvalue.index) value_type = self.accept(rvalue) if is_valid_inferred_type(key_type) and is_valid_inferred_type( value_type ): if not self.current_node_deferred: var.type = self.named_generic_type( "builtins.dict", [key_type, value_type] ) del partial_types[var]
https://github.com/python/mypy/issues/1269
Traceback (most recent call last): File "/home/mg/.virtualenvs/mypy/bin/mypy", line 6, in <module> exec(compile(open(__file__).read(), __file__, 'exec')) File "/home/mg/src/mypy/scripts/mypy", line 6, in <module> main(__file__) File "/home/mg/src/mypy/mypy/main.py", line 50, in main type_check_only(sources, bin_dir, options) File "/home/mg/src/mypy/mypy/main.py", line 94, in type_check_only python_path=options.python_path) File "/home/mg/src/mypy/mypy/build.py", line 210, in build result = manager.process(initial_states) File "/home/mg/src/mypy/mypy/build.py", line 425, in process next.process() File "/home/mg/src/mypy/mypy/build.py", line 930, in process self.type_checker().visit_file(self.tree, self.tree.path) File "/home/mg/src/mypy/mypy/checker.py", line 409, in visit_file self.accept(d) File "/home/mg/src/mypy/mypy/checker.py", line 450, in accept typ = node.accept(self) File "/home/mg/src/mypy/mypy/nodes.py", line 564, in accept return visitor.visit_assignment_stmt(self) File "/home/mg/src/mypy/mypy/checker.py", line 1122, in visit_assignment_stmt self.check_assignment(s.lvalues[-1], s.rvalue, s.type is None) File "/home/mg/src/mypy/mypy/checker.py", line 1167, in check_assignment self.check_indexed_assignment(index_lvalue, rvalue, rvalue) File "/home/mg/src/mypy/mypy/checker.py", line 1499, in check_indexed_assignment self.try_infer_partial_type_from_indexed_assignment(lvalue, rvalue) File "/home/mg/src/mypy/mypy/checker.py", line 1513, in try_infer_partial_type_from_indexed_assignment if var is not None and isinstance(var.type, PartialType): AttributeError: 'TypeInfo' object has no attribute 'type' *** INTERNAL ERROR *** test.py:4: error: Internal error
AttributeError
def lex_indent(self) -> None: """Analyze whitespace chars at the beginning of a line (indents).""" s = self.match(self.indent_exp) while True: s = self.match(self.indent_exp) if s == "" or s[-1] not in self.comment_or_newline: break # Empty line (whitespace only or comment only). self.add_pre_whitespace(s[:-1]) if s[-1] == "#": self.lex_comment() else: self.lex_break() indent = self.calc_indent(s) if indent == self.indents[-1]: # No change in indent: just whitespace. self.add_pre_whitespace(s) elif indent > self.indents[-1]: # An increased indent (new block). self.indents.append(indent) self.add_token(Indent(s)) else: # Decreased indent (end of one or more blocks). pre = self.pre_whitespace self.pre_whitespace = "" while indent < self.indents[-1]: self.add_token(Dedent("")) self.indents.pop() self.pre_whitespace = pre self.add_pre_whitespace(s) if indent != self.indents[-1]: # Error: indent level does not match a previous indent level. self.add_token(LexError("", INVALID_DEDENT))
def lex_indent(self) -> None: """Analyze whitespace chars at the beginning of a line (indents).""" s = self.match(self.indent_exp) if s != "" and s[-1] in self.comment_or_newline: # Empty line (whitespace only or comment only). self.add_pre_whitespace(s[:-1]) if s[-1] == "#": self.lex_comment() else: self.lex_break() self.lex_indent() return indent = self.calc_indent(s) if indent == self.indents[-1]: # No change in indent: just whitespace. self.add_pre_whitespace(s) elif indent > self.indents[-1]: # An increased indent (new block). self.indents.append(indent) self.add_token(Indent(s)) else: # Decreased indent (end of one or more blocks). pre = self.pre_whitespace self.pre_whitespace = "" while indent < self.indents[-1]: self.add_token(Dedent("")) self.indents.pop() self.pre_whitespace = pre self.add_pre_whitespace(s) if indent != self.indents[-1]: # Error: indent level does not match a previous indent level. self.add_token(LexError("", INVALID_DEDENT))
https://github.com/python/mypy/issues/1280
Traceback (most recent call last): File "/usr/local/lib/python3.5/runpy.py", line 170, in _run_module_as_main "__main__", mod_spec) File "/usr/local/lib/python3.5/runpy.py", line 85, in _run_code exec(code, run_globals) File "mypy/__main__.py", line 5, in <module> main(None) File "mypy/main.py", line 50, in main type_check_only(sources, bin_dir, options) File "mypy/main.py", line 94, in type_check_only python_path=options.python_path) File "mypy/build.py", line 210, in build result = manager.process(initial_states) File "mypy/build.py", line 427, in process next.process() File "mypy/build.py", line 759, in process tree = self.parse(self.program_text, self.path) File "mypy/build.py", line 856, in parse fast_parser=FAST_PARSER in self.manager.flags) File "mypy/parse.py", line 98, in parse tree = parser.parse(source) File "mypy/parse.py", line 147, in parse is_stub_file=self.is_stub_file) File "mypy/lex.py", line 170, in lex l.lex(string, first_line) File "mypy/lex.py", line 378, in lex map.get(c, default)() File "mypy/lex.py", line 751, in lex_break self.lex_indent() File "mypy/lex.py", line 698, in lex_indent self.lex_indent() File "mypy/lex.py", line 698, in lex_indent self.lex_indent() [...] File "mypy/lex.py", line 698, in lex_indent self.lex_indent() File "mypy/lex.py", line 697, in lex_indent self.lex_break() File "mypy/lex.py", line 735, in lex_break s = self.match(self.break_exp) RecursionError: maximum recursion depth exceeded
RecursionError
def visit_block(self, b: Block) -> None: if b.is_unreachable: return super().visit_block(b)
def visit_block(self, b: Block) -> None: if b.is_unreachable: return self.sem.block_depth[-1] += 1 for node in b.body: node.accept(self) self.sem.block_depth[-1] -= 1
https://github.com/python/mypy/issues/1319
Traceback (most recent call last): File "/home/samuel/code/harrier/env/bin/mypy", line 6, in <module> main(__file__) File "/home/samuel/code/harrier/env/lib/python3.5/site-packages/mypy/main.py", line 54, in main type_check_only(sources, bin_dir, options) File "/home/samuel/code/harrier/env/lib/python3.5/site-packages/mypy/main.py", line 98, in type_check_only python_path=options.python_path) File "/home/samuel/code/harrier/env/lib/python3.5/site-packages/mypy/build.py", line 206, in build result = manager.process(initial_states) File "/home/samuel/code/harrier/env/lib/python3.5/site-packages/mypy/build.py", line 403, in process next.process() File "/home/samuel/code/harrier/env/lib/python3.5/site-packages/mypy/build.py", line 894, in process self.semantic_analyzer_pass3().visit_file(self.tree, self.tree.path) File "/home/samuel/code/harrier/env/lib/python3.5/site-packages/mypy/semanal.py", line 2341, in visit_file file_node.accept(self) File "/home/samuel/code/harrier/env/lib/python3.5/site-packages/mypy/nodes.py", line 171, in accept return visitor.visit_mypy_file(self) File "/home/samuel/code/harrier/env/lib/python3.5/site-packages/mypy/traverser.py", line 34, in visit_mypy_file d.accept(self) File "/home/samuel/code/harrier/env/lib/python3.5/site-packages/mypy/nodes.py", line 673, in accept return visitor.visit_if_stmt(self) File "/home/samuel/code/harrier/env/lib/python3.5/site-packages/mypy/traverser.py", line 110, in visit_if_stmt o.else_body.accept(self) File "/home/samuel/code/harrier/env/lib/python3.5/site-packages/mypy/nodes.py", line 526, in accept return visitor.visit_block(self) File "/home/samuel/code/harrier/env/lib/python3.5/site-packages/mypy/traverser.py", line 38, in visit_block s.accept(self) File "/home/samuel/code/harrier/env/lib/python3.5/site-packages/mypy/nodes.py", line 673, in accept return visitor.visit_if_stmt(self) File "/home/samuel/code/harrier/env/lib/python3.5/site-packages/mypy/traverser.py", line 110, in visit_if_stmt o.else_body.accept(self) File "/home/samuel/code/harrier/env/lib/python3.5/site-packages/mypy/nodes.py", line 526, in accept return visitor.visit_block(self) File "/home/samuel/code/harrier/env/lib/python3.5/site-packages/mypy/traverser.py", line 38, in visit_block s.accept(self) File "/home/samuel/code/harrier/env/lib/python3.5/site-packages/mypy/nodes.py", line 485, in accept return visitor.visit_class_def(self) File "/home/samuel/code/harrier/env/lib/python3.5/site-packages/mypy/semanal.py", line 2350, in visit_class_def for type in tdef.info.bases: AttributeError: 'NoneType' object has no attribute 'bases'
AttributeError
def read_program(path: str, pyversion: Tuple[int, int]) -> str: try: text = read_with_python_encoding(path, pyversion) except IOError as ioerr: raise CompileError( ["mypy: can't read file '{}': {}".format(path, ioerr.strerror)] ) except UnicodeDecodeError as decodeerr: raise CompileError( ["mypy: can't decode file '{}': {}".format(path, str(decodeerr))] ) return text
def read_program(path: str, pyversion: Tuple[int, int]) -> str: try: text = read_with_python_encoding(path, pyversion) except IOError as ioerr: raise CompileError( ["mypy: can't read file '{}': {}".format(path, ioerr.strerror)] ) return text
https://github.com/python/mypy/issues/1204
Traceback (most recent call last): File "/usr/local/bin/mypy", line 6, in <module> main(__file__) File "/usr/local/lib/python3.5/dist-packages/mypy/main.py", line 54, in main type_check_only(sources, bin_dir, options) File "/usr/local/lib/python3.5/dist-packages/mypy/main.py", line 98, in type_check_only python_path=options.python_path) File "/usr/local/lib/python3.5/dist-packages/mypy/build.py", line 200, in build content = source.load(lib_path, pyversion) File "/usr/local/lib/python3.5/dist-packages/mypy/build.py", line 110, in load return read_program(self.path, pyversion) File "/usr/local/lib/python3.5/dist-packages/mypy/build.py", line 292, in read_program text = read_with_python_encoding(path, pyversion) File "/usr/local/lib/python3.5/dist-packages/mypy/build.py", line 1094, in read_with_python_encoding return source_bytearray.decode(encoding) UnicodeDecodeError: 'ascii' codec can't decode byte 0xf3 in position 1: ordinal not in range(128)
UnicodeDecodeError
def check_argument_kinds( self, funckinds: List[int], sigkinds: List[int], line: int ) -> None: """Check that arguments are consistent. This verifies that they have the same number and the kinds correspond. Arguments: funckinds: kinds of arguments in function definition sigkinds: kinds of arguments in signature (after # type:) """ if len(funckinds) != len(sigkinds): if len(funckinds) > len(sigkinds): self.fail("Type signature has too few arguments", line) else: self.fail("Type signature has too many arguments", line) return for kind, token in [(nodes.ARG_STAR, "*"), (nodes.ARG_STAR2, "**")]: if (funckinds.count(kind) != sigkinds.count(kind)) or ( kind in funckinds and sigkinds.index(kind) != funckinds.index(kind) ): self.fail( "Inconsistent use of '{}' in function signature".format(token), line )
def check_argument_kinds( self, funckinds: List[int], sigkinds: List[int], line: int ) -> None: """Check that * and ** arguments are consistent. Arguments: funckinds: kinds of arguments in function definition sigkinds: kinds of arguments in signature (after # type:) """ for kind, token in [(nodes.ARG_STAR, "*"), (nodes.ARG_STAR2, "**")]: if (funckinds.count(kind) != sigkinds.count(kind)) or ( kind in funckinds and sigkinds.index(kind) != funckinds.index(kind) ): self.fail( "Inconsistent use of '{}' in function signature".format(token), line )
https://github.com/python/mypy/issues/1207
Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.5/bin/mypy", line 6, in <module> main(__file__) File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/mypy/main.py", line 54, in main type_check_only(sources, bin_dir, options) File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/mypy/main.py", line 98, in type_check_only python_path=options.python_path) File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/mypy/build.py", line 208, in build result = manager.process(initial_states) File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/mypy/build.py", line 393, in process next.process() File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/mypy/build.py", line 893, in process self.type_checker().visit_file(self.tree, self.tree.path) File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/mypy/checker.py", line 405, in visit_file self.accept(d) File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/mypy/checker.py", line 446, in accept typ = node.accept(self) File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/mypy/nodes.py", line 540, in accept return visitor.visit_expression_stmt(self) File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/mypy/checker.py", line 1533, in visit_expression_stmt self.accept(s.expr) File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/mypy/checker.py", line 446, in accept typ = node.accept(self) File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/mypy/nodes.py", line 965, in accept return visitor.visit_call_expr(self) File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/mypy/checker.py", line 1931, in visit_call_expr return self.expr_checker.visit_call_expr(e) File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/mypy/checkexpr.py", line 142, in visit_call_expr return self.check_call_expr_with_callee_type(callee_type, e) File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/mypy/checkexpr.py", line 193, in check_call_expr_with_callee_type e.arg_names, callable_node=e.callee)[0] File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/mypy/checkexpr.py", line 236, in check_call callee, args, arg_kinds, formal_to_actual) File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/mypy/checkexpr.py", line 328, in infer_arg_types_in_context2 res[ai] = self.accept(args[ai], callee.arg_types[i]) IndexError: list index out of range *** INTERNAL ERROR ***
IndexError
def visit_func_def(self, defn: FuncDef) -> Type: """Type check a function definition.""" self.check_func_item(defn, name=defn.name()) if defn.info: if not defn.is_dynamic(): self.check_method_override(defn) self.check_inplace_operator_method(defn) if defn.original_def: # Override previous definition. new_type = self.function_type(defn) if isinstance(defn.original_def, FuncDef): # Function definition overrides function definition. if not is_same_type(new_type, self.function_type(defn.original_def)): self.msg.incompatible_conditional_function_def(defn) else: # Function definition overrides a variable initialized via assignment. orig_type = defn.original_def.type if isinstance(orig_type, PartialType): if orig_type.type is None: # Ah this is a partial type. Give it the type of the function. var = defn.original_def partial_types = self.find_partial_types(var) if partial_types is not None: var.type = new_type del partial_types[var] else: # Trying to redefine something like partial empty list as function. self.fail(messages.INCOMPATIBLE_REDEFINITION, defn) else: # TODO: Update conditional type binder. self.check_subtype( orig_type, new_type, defn, messages.INCOMPATIBLE_REDEFINITION, "original type", "redefinition with type", )
def visit_func_def(self, defn: FuncDef) -> Type: """Type check a function definition.""" self.check_func_item(defn, name=defn.name()) if defn.info: if not defn.is_dynamic(): self.check_method_override(defn) self.check_inplace_operator_method(defn) if defn.original_def: # Override previous definition. new_type = self.function_type(defn) if isinstance(defn.original_def, FuncDef): # Function definition overrides function definition. if not is_same_type(new_type, self.function_type(defn.original_def)): self.msg.incompatible_conditional_function_def(defn) else: # Function definition overrides a variable initialized via assignment. orig_type = defn.original_def.type if isinstance(orig_type, PartialType): if orig_type.type is None: # Ah this is a partial type. Give it the type of the function. defn.original_def.type = new_type partial_types = self.partial_types[-1] del partial_types[defn.original_def] else: # Trying to redefine something like partial empty list as function. self.fail(messages.INCOMPATIBLE_REDEFINITION, defn) else: # TODO: Update conditional type binder. self.check_subtype( orig_type, new_type, defn, messages.INCOMPATIBLE_REDEFINITION, "original type", "redefinition with type", )
https://github.com/python/mypy/issues/1126
Traceback (most recent call last): File "./scripts/mypy", line 6, in <module> main(__file__) File "/home/dshea/src/mypy/mypy/main.py", line 53, in main type_check_only(sources, bin_dir, options) File "/home/dshea/src/mypy/mypy/main.py", line 96, in type_check_only python_path=options.python_path) File "/home/dshea/src/mypy/mypy/build.py", line 203, in build result = manager.process(initial_states) File "/home/dshea/src/mypy/mypy/build.py", line 386, in process next.process() File "/home/dshea/src/mypy/mypy/build.py", line 883, in process self.type_checker().visit_file(self.tree, self.tree.path) File "/home/dshea/src/mypy/mypy/checker.py", line 385, in visit_file self.accept(d) File "/home/dshea/src/mypy/mypy/checker.py", line 394, in accept typ = node.accept(self) File "/home/dshea/src/mypy/mypy/nodes.py", line 383, in accept return visitor.visit_func_def(self) File "/home/dshea/src/mypy/mypy/checker.py", line 449, in visit_func_def self.check_func_item(defn, name=defn.name()) File "/home/dshea/src/mypy/mypy/checker.py", line 505, in check_func_item self.check_func_def(defn, typ, name) File "/home/dshea/src/mypy/mypy/checker.py", line 588, in check_func_def self.accept_in_frame(item.body) File "/home/dshea/src/mypy/mypy/checker.py", line 409, in accept_in_frame answer = self.accept(node, type_context) File "/home/dshea/src/mypy/mypy/checker.py", line 394, in accept typ = node.accept(self) File "/home/dshea/src/mypy/mypy/nodes.py", line 527, in accept return visitor.visit_block(self) File "/home/dshea/src/mypy/mypy/checker.py", line 983, in visit_block self.accept(s) File "/home/dshea/src/mypy/mypy/checker.py", line 394, in accept typ = node.accept(self) File "/home/dshea/src/mypy/mypy/nodes.py", line 565, in accept return visitor.visit_assignment_stmt(self) File "/home/dshea/src/mypy/mypy/checker.py", line 992, in visit_assignment_stmt self.check_assignment(s.lvalues[-1], s.rvalue, s.type is None) File "/home/dshea/src/mypy/mypy/checker.py", line 1021, in check_assignment del partial_types[lvalue_type.var] KeyError: <mypy.nodes.Var object at 0x7ffbeee8f6d8> *** INTERNAL ERROR *** /usr/lib64/python3.5/mimetypes.py:359: error: Internal error -- please report a bug at https://github.com/JukkaL/mypy/issues NOTE: you can use "mypy --pdb ..." to drop into the debugger when this happens.
KeyError
def check_assignment( self, lvalue: Node, rvalue: Node, infer_lvalue_type: bool = True ) -> None: """Type check a single assignment: lvalue = rvalue.""" if isinstance(lvalue, TupleExpr) or isinstance(lvalue, ListExpr): ltuple = cast(Union[TupleExpr, ListExpr], lvalue) self.check_assignment_to_multiple_lvalues( ltuple.items, rvalue, lvalue, infer_lvalue_type ) else: lvalue_type, index_lvalue, inferred = self.check_lvalue(lvalue) if lvalue_type: if isinstance(lvalue_type, PartialType) and lvalue_type.type is None: # Try to infer a proper type for a variable with a partial None type. rvalue_type = self.accept(rvalue) if isinstance(rvalue_type, NoneTyp): # This doesn't actually provide any additional information -- multiple # None initializers preserve the partial None type. return if is_valid_inferred_type(rvalue_type): var = lvalue_type.var partial_types = self.find_partial_types(var) if partial_types is not None: var.type = rvalue_type del partial_types[var] # Try to infer a partial type. No need to check the return value, as # an error will be reported elsewhere. self.infer_partial_type(lvalue_type.var, lvalue, rvalue_type) return rvalue_type = self.check_simple_assignment(lvalue_type, rvalue, lvalue) if rvalue_type and infer_lvalue_type: self.binder.assign_type(lvalue, rvalue_type, self.typing_mode_weak()) elif index_lvalue: self.check_indexed_assignment(index_lvalue, rvalue, rvalue) if inferred: self.infer_variable_type(inferred, lvalue, self.accept(rvalue), rvalue)
def check_assignment( self, lvalue: Node, rvalue: Node, infer_lvalue_type: bool = True ) -> None: """Type check a single assignment: lvalue = rvalue.""" if isinstance(lvalue, TupleExpr) or isinstance(lvalue, ListExpr): ltuple = cast(Union[TupleExpr, ListExpr], lvalue) self.check_assignment_to_multiple_lvalues( ltuple.items, rvalue, lvalue, infer_lvalue_type ) else: lvalue_type, index_lvalue, inferred = self.check_lvalue(lvalue) if lvalue_type: if isinstance(lvalue_type, PartialType) and lvalue_type.type is None: # Try to infer a proper type for a variable with a partial None type. rvalue_type = self.accept(rvalue) if isinstance(rvalue_type, NoneTyp): # This doesn't actually provide any additional information -- multiple # None initializers preserve the partial None type. return if is_valid_inferred_type(rvalue_type): lvalue_type.var.type = rvalue_type partial_types = self.partial_types[-1] del partial_types[lvalue_type.var] # Try to infer a partial type. No need to check the return value, as # an error will be reported elsewhere. self.infer_partial_type(lvalue_type.var, lvalue, rvalue_type) return rvalue_type = self.check_simple_assignment(lvalue_type, rvalue, lvalue) if rvalue_type and infer_lvalue_type: self.binder.assign_type(lvalue, rvalue_type, self.typing_mode_weak()) elif index_lvalue: self.check_indexed_assignment(index_lvalue, rvalue, rvalue) if inferred: self.infer_variable_type(inferred, lvalue, self.accept(rvalue), rvalue)
https://github.com/python/mypy/issues/1126
Traceback (most recent call last): File "./scripts/mypy", line 6, in <module> main(__file__) File "/home/dshea/src/mypy/mypy/main.py", line 53, in main type_check_only(sources, bin_dir, options) File "/home/dshea/src/mypy/mypy/main.py", line 96, in type_check_only python_path=options.python_path) File "/home/dshea/src/mypy/mypy/build.py", line 203, in build result = manager.process(initial_states) File "/home/dshea/src/mypy/mypy/build.py", line 386, in process next.process() File "/home/dshea/src/mypy/mypy/build.py", line 883, in process self.type_checker().visit_file(self.tree, self.tree.path) File "/home/dshea/src/mypy/mypy/checker.py", line 385, in visit_file self.accept(d) File "/home/dshea/src/mypy/mypy/checker.py", line 394, in accept typ = node.accept(self) File "/home/dshea/src/mypy/mypy/nodes.py", line 383, in accept return visitor.visit_func_def(self) File "/home/dshea/src/mypy/mypy/checker.py", line 449, in visit_func_def self.check_func_item(defn, name=defn.name()) File "/home/dshea/src/mypy/mypy/checker.py", line 505, in check_func_item self.check_func_def(defn, typ, name) File "/home/dshea/src/mypy/mypy/checker.py", line 588, in check_func_def self.accept_in_frame(item.body) File "/home/dshea/src/mypy/mypy/checker.py", line 409, in accept_in_frame answer = self.accept(node, type_context) File "/home/dshea/src/mypy/mypy/checker.py", line 394, in accept typ = node.accept(self) File "/home/dshea/src/mypy/mypy/nodes.py", line 527, in accept return visitor.visit_block(self) File "/home/dshea/src/mypy/mypy/checker.py", line 983, in visit_block self.accept(s) File "/home/dshea/src/mypy/mypy/checker.py", line 394, in accept typ = node.accept(self) File "/home/dshea/src/mypy/mypy/nodes.py", line 565, in accept return visitor.visit_assignment_stmt(self) File "/home/dshea/src/mypy/mypy/checker.py", line 992, in visit_assignment_stmt self.check_assignment(s.lvalues[-1], s.rvalue, s.type is None) File "/home/dshea/src/mypy/mypy/checker.py", line 1021, in check_assignment del partial_types[lvalue_type.var] KeyError: <mypy.nodes.Var object at 0x7ffbeee8f6d8> *** INTERNAL ERROR *** /usr/lib64/python3.5/mimetypes.py:359: error: Internal error -- please report a bug at https://github.com/JukkaL/mypy/issues NOTE: you can use "mypy --pdb ..." to drop into the debugger when this happens.
KeyError
def try_infer_partial_type_from_indexed_assignment( self, lvalue: IndexExpr, rvalue: Node ) -> None: # TODO: Should we share some of this with try_infer_partial_type? if isinstance(lvalue.base, RefExpr): var = cast(Var, lvalue.base.node) partial_types = self.find_partial_types(var) if partial_types is not None: typename = cast(Instance, var.type).type.fullname() if typename == "builtins.dict": # TODO: Don't infer things twice. key_type = self.accept(lvalue.index) value_type = self.accept(rvalue) if is_valid_inferred_type(key_type) and is_valid_inferred_type( value_type ): var.type = self.named_generic_type( "builtins.dict", [key_type, value_type] ) del partial_types[var]
def try_infer_partial_type_from_indexed_assignment( self, lvalue: IndexExpr, rvalue: Node ) -> None: # TODO: Should we share some of this with try_infer_partial_type? partial_types = self.partial_types[-1] if not partial_types: # Fast path leave -- no partial types in the current scope. return if isinstance(lvalue.base, RefExpr): var = lvalue.base.node if var in partial_types: var = cast(Var, var) typename = cast(Instance, var.type).type.fullname() if typename == "builtins.dict": # TODO: Don't infer things twice. key_type = self.accept(lvalue.index) value_type = self.accept(rvalue) if is_valid_inferred_type(key_type) and is_valid_inferred_type( value_type ): var.type = self.named_generic_type( "builtins.dict", [key_type, value_type] ) del partial_types[var]
https://github.com/python/mypy/issues/1126
Traceback (most recent call last): File "./scripts/mypy", line 6, in <module> main(__file__) File "/home/dshea/src/mypy/mypy/main.py", line 53, in main type_check_only(sources, bin_dir, options) File "/home/dshea/src/mypy/mypy/main.py", line 96, in type_check_only python_path=options.python_path) File "/home/dshea/src/mypy/mypy/build.py", line 203, in build result = manager.process(initial_states) File "/home/dshea/src/mypy/mypy/build.py", line 386, in process next.process() File "/home/dshea/src/mypy/mypy/build.py", line 883, in process self.type_checker().visit_file(self.tree, self.tree.path) File "/home/dshea/src/mypy/mypy/checker.py", line 385, in visit_file self.accept(d) File "/home/dshea/src/mypy/mypy/checker.py", line 394, in accept typ = node.accept(self) File "/home/dshea/src/mypy/mypy/nodes.py", line 383, in accept return visitor.visit_func_def(self) File "/home/dshea/src/mypy/mypy/checker.py", line 449, in visit_func_def self.check_func_item(defn, name=defn.name()) File "/home/dshea/src/mypy/mypy/checker.py", line 505, in check_func_item self.check_func_def(defn, typ, name) File "/home/dshea/src/mypy/mypy/checker.py", line 588, in check_func_def self.accept_in_frame(item.body) File "/home/dshea/src/mypy/mypy/checker.py", line 409, in accept_in_frame answer = self.accept(node, type_context) File "/home/dshea/src/mypy/mypy/checker.py", line 394, in accept typ = node.accept(self) File "/home/dshea/src/mypy/mypy/nodes.py", line 527, in accept return visitor.visit_block(self) File "/home/dshea/src/mypy/mypy/checker.py", line 983, in visit_block self.accept(s) File "/home/dshea/src/mypy/mypy/checker.py", line 394, in accept typ = node.accept(self) File "/home/dshea/src/mypy/mypy/nodes.py", line 565, in accept return visitor.visit_assignment_stmt(self) File "/home/dshea/src/mypy/mypy/checker.py", line 992, in visit_assignment_stmt self.check_assignment(s.lvalues[-1], s.rvalue, s.type is None) File "/home/dshea/src/mypy/mypy/checker.py", line 1021, in check_assignment del partial_types[lvalue_type.var] KeyError: <mypy.nodes.Var object at 0x7ffbeee8f6d8> *** INTERNAL ERROR *** /usr/lib64/python3.5/mimetypes.py:359: error: Internal error -- please report a bug at https://github.com/JukkaL/mypy/issues NOTE: you can use "mypy --pdb ..." to drop into the debugger when this happens.
KeyError
def analyze_ref_expr(self, e: RefExpr, lvalue: bool = False) -> Type: result = None # type: Type node = e.node if isinstance(node, Var): # Variable reference. result = self.analyze_var_ref(node, e) if isinstance(result, PartialType): if result.type is None: # 'None' partial type. It has a well-defined type. In an lvalue context # we want to preserve the knowledge of it being a partial type. if not lvalue: result = NoneTyp() else: partial_types = self.chk.find_partial_types(node) if partial_types is not None: context = partial_types[node] self.msg.fail(messages.NEED_ANNOTATION_FOR_VAR, context) result = AnyType() elif isinstance(node, FuncDef): # Reference to a global function. result = function_type(node, self.named_type("builtins.function")) elif isinstance(node, OverloadedFuncDef): result = node.type elif isinstance(node, TypeInfo): # Reference to a type object. result = type_object_type(node, self.named_type) elif isinstance(node, MypyFile): # Reference to a module object. result = self.named_type("builtins.module") elif isinstance(node, Decorator): result = self.analyze_var_ref(node.var, e) else: # Unknown reference; use any type implicitly to avoid # generating extra type errors. result = AnyType() return result
def analyze_ref_expr(self, e: RefExpr, lvalue: bool = False) -> Type: result = None # type: Type node = e.node if isinstance(node, Var): # Variable reference. result = self.analyze_var_ref(node, e) if isinstance(result, PartialType): if result.type is None: # 'None' partial type. It has a well-defined type. In an lvalue context # we want to preserve the knowledge of it being a partial type. if not lvalue: result = NoneTyp() else: partial_types = self.chk.partial_types[-1] if node in partial_types: context = partial_types[node] self.msg.fail(messages.NEED_ANNOTATION_FOR_VAR, context) result = AnyType() elif isinstance(node, FuncDef): # Reference to a global function. result = function_type(node, self.named_type("builtins.function")) elif isinstance(node, OverloadedFuncDef): result = node.type elif isinstance(node, TypeInfo): # Reference to a type object. result = type_object_type(node, self.named_type) elif isinstance(node, MypyFile): # Reference to a module object. result = self.named_type("builtins.module") elif isinstance(node, Decorator): result = self.analyze_var_ref(node.var, e) else: # Unknown reference; use any type implicitly to avoid # generating extra type errors. result = AnyType() return result
https://github.com/python/mypy/issues/1126
Traceback (most recent call last): File "./scripts/mypy", line 6, in <module> main(__file__) File "/home/dshea/src/mypy/mypy/main.py", line 53, in main type_check_only(sources, bin_dir, options) File "/home/dshea/src/mypy/mypy/main.py", line 96, in type_check_only python_path=options.python_path) File "/home/dshea/src/mypy/mypy/build.py", line 203, in build result = manager.process(initial_states) File "/home/dshea/src/mypy/mypy/build.py", line 386, in process next.process() File "/home/dshea/src/mypy/mypy/build.py", line 883, in process self.type_checker().visit_file(self.tree, self.tree.path) File "/home/dshea/src/mypy/mypy/checker.py", line 385, in visit_file self.accept(d) File "/home/dshea/src/mypy/mypy/checker.py", line 394, in accept typ = node.accept(self) File "/home/dshea/src/mypy/mypy/nodes.py", line 383, in accept return visitor.visit_func_def(self) File "/home/dshea/src/mypy/mypy/checker.py", line 449, in visit_func_def self.check_func_item(defn, name=defn.name()) File "/home/dshea/src/mypy/mypy/checker.py", line 505, in check_func_item self.check_func_def(defn, typ, name) File "/home/dshea/src/mypy/mypy/checker.py", line 588, in check_func_def self.accept_in_frame(item.body) File "/home/dshea/src/mypy/mypy/checker.py", line 409, in accept_in_frame answer = self.accept(node, type_context) File "/home/dshea/src/mypy/mypy/checker.py", line 394, in accept typ = node.accept(self) File "/home/dshea/src/mypy/mypy/nodes.py", line 527, in accept return visitor.visit_block(self) File "/home/dshea/src/mypy/mypy/checker.py", line 983, in visit_block self.accept(s) File "/home/dshea/src/mypy/mypy/checker.py", line 394, in accept typ = node.accept(self) File "/home/dshea/src/mypy/mypy/nodes.py", line 565, in accept return visitor.visit_assignment_stmt(self) File "/home/dshea/src/mypy/mypy/checker.py", line 992, in visit_assignment_stmt self.check_assignment(s.lvalues[-1], s.rvalue, s.type is None) File "/home/dshea/src/mypy/mypy/checker.py", line 1021, in check_assignment del partial_types[lvalue_type.var] KeyError: <mypy.nodes.Var object at 0x7ffbeee8f6d8> *** INTERNAL ERROR *** /usr/lib64/python3.5/mimetypes.py:359: error: Internal error -- please report a bug at https://github.com/JukkaL/mypy/issues NOTE: you can use "mypy --pdb ..." to drop into the debugger when this happens.
KeyError
def try_infer_partial_type(self, e: CallExpr) -> None: if isinstance(e.callee, MemberExpr) and isinstance(e.callee.expr, RefExpr): var = cast(Var, e.callee.expr.node) partial_types = self.chk.find_partial_types(var) if partial_types is not None: partial_type_type = cast(PartialType, var.type).type if partial_type_type is None: # A partial None type -> can't infer anything. return typename = partial_type_type.fullname() methodname = e.callee.name # Sometimes we can infer a full type for a partial List, Dict or Set type. # TODO: Don't infer argument expression twice. if ( typename in self.item_args and methodname in self.item_args[typename] and e.arg_kinds == [ARG_POS] ): item_type = self.accept(e.args[0]) if mypy.checker.is_valid_inferred_type(item_type): var.type = self.chk.named_generic_type(typename, [item_type]) del partial_types[var] elif ( typename in self.container_args and methodname in self.container_args[typename] and e.arg_kinds == [ARG_POS] ): arg_type = self.accept(e.args[0]) if isinstance(arg_type, Instance): arg_typename = arg_type.type.fullname() if arg_typename in self.container_args[typename][methodname]: if all( mypy.checker.is_valid_inferred_type(item_type) for item_type in arg_type.args ): var.type = self.chk.named_generic_type( typename, list(arg_type.args) ) del partial_types[var]
def try_infer_partial_type(self, e: CallExpr) -> None: partial_types = self.chk.partial_types[-1] if not partial_types: # Fast path leave -- no partial types in the current scope. return if isinstance(e.callee, MemberExpr) and isinstance(e.callee.expr, RefExpr): var = e.callee.expr.node if var in partial_types: var = cast(Var, var) partial_type_type = cast(PartialType, var.type).type if partial_type_type is None: # A partial None type -> can't infer anything. return typename = partial_type_type.fullname() methodname = e.callee.name # Sometimes we can infer a full type for a partial List, Dict or Set type. # TODO: Don't infer argument expression twice. if ( typename in self.item_args and methodname in self.item_args[typename] and e.arg_kinds == [ARG_POS] ): item_type = self.accept(e.args[0]) if mypy.checker.is_valid_inferred_type(item_type): var.type = self.chk.named_generic_type(typename, [item_type]) del partial_types[var] elif ( typename in self.container_args and methodname in self.container_args[typename] and e.arg_kinds == [ARG_POS] ): arg_type = self.accept(e.args[0]) if isinstance(arg_type, Instance): arg_typename = arg_type.type.fullname() if arg_typename in self.container_args[typename][methodname]: if all( mypy.checker.is_valid_inferred_type(item_type) for item_type in arg_type.args ): var.type = self.chk.named_generic_type( typename, list(arg_type.args) ) del partial_types[var]
https://github.com/python/mypy/issues/1126
Traceback (most recent call last): File "./scripts/mypy", line 6, in <module> main(__file__) File "/home/dshea/src/mypy/mypy/main.py", line 53, in main type_check_only(sources, bin_dir, options) File "/home/dshea/src/mypy/mypy/main.py", line 96, in type_check_only python_path=options.python_path) File "/home/dshea/src/mypy/mypy/build.py", line 203, in build result = manager.process(initial_states) File "/home/dshea/src/mypy/mypy/build.py", line 386, in process next.process() File "/home/dshea/src/mypy/mypy/build.py", line 883, in process self.type_checker().visit_file(self.tree, self.tree.path) File "/home/dshea/src/mypy/mypy/checker.py", line 385, in visit_file self.accept(d) File "/home/dshea/src/mypy/mypy/checker.py", line 394, in accept typ = node.accept(self) File "/home/dshea/src/mypy/mypy/nodes.py", line 383, in accept return visitor.visit_func_def(self) File "/home/dshea/src/mypy/mypy/checker.py", line 449, in visit_func_def self.check_func_item(defn, name=defn.name()) File "/home/dshea/src/mypy/mypy/checker.py", line 505, in check_func_item self.check_func_def(defn, typ, name) File "/home/dshea/src/mypy/mypy/checker.py", line 588, in check_func_def self.accept_in_frame(item.body) File "/home/dshea/src/mypy/mypy/checker.py", line 409, in accept_in_frame answer = self.accept(node, type_context) File "/home/dshea/src/mypy/mypy/checker.py", line 394, in accept typ = node.accept(self) File "/home/dshea/src/mypy/mypy/nodes.py", line 527, in accept return visitor.visit_block(self) File "/home/dshea/src/mypy/mypy/checker.py", line 983, in visit_block self.accept(s) File "/home/dshea/src/mypy/mypy/checker.py", line 394, in accept typ = node.accept(self) File "/home/dshea/src/mypy/mypy/nodes.py", line 565, in accept return visitor.visit_assignment_stmt(self) File "/home/dshea/src/mypy/mypy/checker.py", line 992, in visit_assignment_stmt self.check_assignment(s.lvalues[-1], s.rvalue, s.type is None) File "/home/dshea/src/mypy/mypy/checker.py", line 1021, in check_assignment del partial_types[lvalue_type.var] KeyError: <mypy.nodes.Var object at 0x7ffbeee8f6d8> *** INTERNAL ERROR *** /usr/lib64/python3.5/mimetypes.py:359: error: Internal error -- please report a bug at https://github.com/JukkaL/mypy/issues NOTE: you can use "mypy --pdb ..." to drop into the debugger when this happens.
KeyError
def lex(self, text: Union[str, bytes], first_line: int) -> None: """Lexically analyze a string, storing the tokens at the tok list.""" self.i = 0 self.line = first_line if isinstance(text, bytes): if text.startswith(b"\xef\xbb\xbf"): self.enc = "utf8" bom = True else: self.enc, enc_line = find_python_encoding(text, self.pyversion) bom = False try: decoded_text = text.decode(self.enc) except UnicodeDecodeError as err: self.report_unicode_decode_error(err, text) return except LookupError: self.report_unknown_encoding(enc_line) return text = decoded_text if bom: self.add_token(Bom(text[0])) self.s = text # Parse initial indent; otherwise first-line indent would not generate # an error. self.lex_indent() # Use some local variables as a simple optimization. map = self.map default = self.unknown_character # Lex the file. Repeatedly call the lexer method for the current char. while self.i < len(text): # Get the character code of the next character to lex. c = text[self.i] # Dispatch to the relevant lexer method. This will consume some # characters in the text, add a token to self.tok and increment # self.i. map.get(c, default)() # Append a break if there is no statement/block terminator at the end # of input. if len(self.tok) > 0 and ( not isinstance(self.tok[-1], Break) and not isinstance(self.tok[-1], Dedent) ): self.add_token(Break("")) # Attach any dangling comments/whitespace to a final Break token. if self.tok and isinstance(self.tok[-1], Break): self.tok[-1].string += self.pre_whitespace self.pre_whitespace = "" # Close remaining open blocks with Dedent tokens. self.lex_indent() self.add_token(Eof(""))
def lex(self, text: Union[str, bytes], first_line: int) -> None: """Lexically analyze a string, storing the tokens at the tok list.""" self.i = 0 self.line = first_line if isinstance(text, bytes): if text.startswith(b"\xef\xbb\xbf"): self.enc = "utf8" bom = True else: self.enc, enc_line = find_python_encoding(text, self.pyversion) bom = False try: decoded_text = text.decode(self.enc) except UnicodeDecodeError as err: self.report_unicode_decode_error(err, text) return except LookupError: self.report_unknown_encoding(enc_line) return text = decoded_text if bom: self.add_token(Bom(text[0])) self.s = text # Parse initial indent; otherwise first-line indent would not generate # an error. self.lex_indent() # Make a local copy of map as a simple optimization. map = self.map # Lex the file. Repeatedly call the lexer method for the current char. while self.i < len(text): # Get the character code of the next character to lex. c = ord(text[self.i]) # Dispatch to the relevant lexer method. This will consume some # characters in the text, add a token to self.tok and increment # self.i. map[c]() # Append a break if there is no statement/block terminator at the end # of input. if len(self.tok) > 0 and ( not isinstance(self.tok[-1], Break) and not isinstance(self.tok[-1], Dedent) ): self.add_token(Break("")) # Attach any dangling comments/whitespace to a final Break token. if self.tok and isinstance(self.tok[-1], Break): self.tok[-1].string += self.pre_whitespace self.pre_whitespace = "" # Close remaining open blocks with Dedent tokens. self.lex_indent() self.add_token(Eof(""))
https://github.com/python/mypy/issues/1127
Traceback (most recent call last): File "/usr/local/lib/python3.5/runpy.py", line 184, in _run_module_as_main "__main__", mod_spec) File "/usr/local/lib/python3.5/runpy.py", line 85, in _run_code exec(code, run_globals) File "/Users/guido/src/mypy/mypy/__main__.py", line 5, in <module> main(None) File "/Users/guido/src/mypy/mypy/main.py", line 53, in main type_check_only(sources, bin_dir, options) File "/Users/guido/src/mypy/mypy/main.py", line 96, in type_check_only python_path=options.python_path) File "/Users/guido/src/mypy/mypy/build.py", line 203, in build result = manager.process(initial_states) File "/Users/guido/src/mypy/mypy/build.py", line 386, in process next.process() File "/Users/guido/src/mypy/mypy/build.py", line 710, in process tree = self.parse(self.program_text, self.path) File "/Users/guido/src/mypy/mypy/build.py", line 807, in parse custom_typing_module=self.manager.custom_typing_module) File "/Users/guido/src/mypy/mypy/parse.py", line 83, in parse tree = parser.parse(source) File "/Users/guido/src/mypy/mypy/parse.py", line 130, in parse is_stub_file=self.is_stub_file) File "/Users/guido/src/mypy/mypy/lex.py", line 170, in lex l.lex(string, first_line) File "/Users/guido/src/mypy/mypy/lex.py", line 377, in lex map[c]() IndexError: list index out of range
IndexError
def __init__( self, pyversion: Tuple[int, int] = defaults.PYTHON3_VERSION, is_stub_file: bool = False, ) -> None: self.map = {} self.tok = [] self.indents = [0] self.open_brackets = [] self.pyversion = pyversion self.is_stub_file = is_stub_file self.ignored_lines = set() # Fill in the map from valid character codes to relevant lexer methods. extra_misc = "" if pyversion[0] >= 3 else "`" for seq, method in [ ("ABCDEFGHIJKLMNOPQRSTUVWXYZ", self.lex_name), ("abcdefghijklmnopqrstuvwxyz_", self.lex_name), ("0123456789", self.lex_number), (".", self.lex_number_or_dot), (" " + "\t" + "\x0c", self.lex_space), ('"', self.lex_str_double), ("'", self.lex_str_single), ("\r" + "\n", self.lex_break), (";", self.lex_semicolon), (":", self.lex_colon), ("#", self.lex_comment), ("\\", self.lex_backslash), ("([{", self.lex_open_bracket), (")]}", self.lex_close_bracket), ("-+*/<>%&|^~=!,@" + extra_misc, self.lex_misc), ]: for c in seq: self.map[c] = method if pyversion[0] == 2: self.keywords = keywords_common | keywords2 # Decimal/hex/octal/binary literal or integer complex literal self.number_exp1 = re.compile("(0[xXoObB][0-9a-fA-F]+|[0-9]+)[lL]?") if pyversion[0] == 3: self.keywords = keywords_common | keywords3 self.number_exp1 = re.compile("0[xXoObB][0-9a-fA-F]+|[0-9]+")
def __init__( self, pyversion: Tuple[int, int] = defaults.PYTHON3_VERSION, is_stub_file: bool = False, ) -> None: self.map = [self.unknown_character] * 256 self.tok = [] self.indents = [0] self.open_brackets = [] self.pyversion = pyversion self.is_stub_file = is_stub_file self.ignored_lines = set() # Fill in the map from valid character codes to relevant lexer methods. extra_misc = "" if pyversion[0] >= 3 else "`" for seq, method in [ ("ABCDEFGHIJKLMNOPQRSTUVWXYZ", self.lex_name), ("abcdefghijklmnopqrstuvwxyz_", self.lex_name), ("0123456789", self.lex_number), (".", self.lex_number_or_dot), (" " + "\t" + "\x0c", self.lex_space), ('"', self.lex_str_double), ("'", self.lex_str_single), ("\r" + "\n", self.lex_break), (";", self.lex_semicolon), (":", self.lex_colon), ("#", self.lex_comment), ("\\", self.lex_backslash), ("([{", self.lex_open_bracket), (")]}", self.lex_close_bracket), ("-+*/<>%&|^~=!,@" + extra_misc, self.lex_misc), ]: for c in seq: self.map[ord(c)] = method if pyversion[0] == 2: self.keywords = keywords_common | keywords2 # Decimal/hex/octal/binary literal or integer complex literal self.number_exp1 = re.compile("(0[xXoObB][0-9a-fA-F]+|[0-9]+)[lL]?") if pyversion[0] == 3: self.keywords = keywords_common | keywords3 self.number_exp1 = re.compile("0[xXoObB][0-9a-fA-F]+|[0-9]+")
https://github.com/python/mypy/issues/1127
Traceback (most recent call last): File "/usr/local/lib/python3.5/runpy.py", line 184, in _run_module_as_main "__main__", mod_spec) File "/usr/local/lib/python3.5/runpy.py", line 85, in _run_code exec(code, run_globals) File "/Users/guido/src/mypy/mypy/__main__.py", line 5, in <module> main(None) File "/Users/guido/src/mypy/mypy/main.py", line 53, in main type_check_only(sources, bin_dir, options) File "/Users/guido/src/mypy/mypy/main.py", line 96, in type_check_only python_path=options.python_path) File "/Users/guido/src/mypy/mypy/build.py", line 203, in build result = manager.process(initial_states) File "/Users/guido/src/mypy/mypy/build.py", line 386, in process next.process() File "/Users/guido/src/mypy/mypy/build.py", line 710, in process tree = self.parse(self.program_text, self.path) File "/Users/guido/src/mypy/mypy/build.py", line 807, in parse custom_typing_module=self.manager.custom_typing_module) File "/Users/guido/src/mypy/mypy/parse.py", line 83, in parse tree = parser.parse(source) File "/Users/guido/src/mypy/mypy/parse.py", line 130, in parse is_stub_file=self.is_stub_file) File "/Users/guido/src/mypy/mypy/lex.py", line 170, in lex l.lex(string, first_line) File "/Users/guido/src/mypy/mypy/lex.py", line 377, in lex map[c]() IndexError: list index out of range
IndexError
def on_file(self, tree: MypyFile, type_map: Dict[Node, Type]) -> None: import lxml.etree as etree self.last_xml = None path = os.path.relpath(tree.path) if stats.is_special_module(path): return if path.startswith(".."): return if "stubs" in path.split("/"): return visitor = stats.StatisticsVisitor(inferred=True, typemap=type_map, all_nodes=True) tree.accept(visitor) root = etree.Element("mypy-report-file", name=path, module=tree._fullname) doc = etree.ElementTree(root) file_info = FileInfo(path, tree._fullname) with open(path) as input_file: for lineno, line_text in enumerate(input_file, 1): status = visitor.line_map.get(lineno, stats.TYPE_EMPTY) file_info.counts[status] += 1 etree.SubElement( root, "line", number=str(lineno), precision=stats.precision_names[status], content=line_text[:-1], ) # Assumes a layout similar to what XmlReporter uses. xslt_path = os.path.relpath("mypy-html.xslt", path) transform_pi = etree.ProcessingInstruction( "xml-stylesheet", 'type="text/xsl" href="%s"' % cgi.escape(xslt_path, True) ) root.addprevious(transform_pi) self.schema.assertValid(doc) self.last_xml = doc self.files.append(file_info)
def on_file(self, tree: MypyFile, type_map: Dict[Node, Type]) -> None: import lxml.etree as etree self.last_xml = None path = os.path.relpath(tree.path) if stats.is_special_module(path): return if path.startswith(".."): return if "stubs" in path.split("/"): return visitor = stats.StatisticsVisitor(inferred=True, typemap=type_map, all_nodes=True) tree.accept(visitor) root = etree.Element("mypy-report-file", name=path, module=tree._fullname) doc = etree.ElementTree(root) file_info = FileInfo(path, tree._fullname) with open(path) as input_file: for lineno, line_text in enumerate(input_file, 1): status = visitor.line_map.get(lineno, stats.TYPE_EMPTY) file_info.counts[status] += 1 etree.SubElement( root, "line", number=str(lineno), precision=stats.precision_names[status], content=line_text[:-1], ) # Assumes a layout similar to what XmlReporter uses. xslt_path = os.path.relpath("mypy-html.xslt", path) xml_pi = etree.ProcessingInstruction("xml", 'version="1.0" encoding="utf-8"') transform_pi = etree.ProcessingInstruction( "xml-stylesheet", 'type="text/xsl" href="%s"' % cgi.escape(xslt_path, True) ) root.addprevious(xml_pi) root.addprevious(transform_pi) self.schema.assertValid(doc) self.last_xml = doc self.files.append(file_info)
https://github.com/python/mypy/issues/1002
$ mypy --html-report mypy_dir defaultdict_example.py Traceback (most recent call last): File "/Users/rwilliams/src/oss/mypy/.venv/bin/mypy", line 6, in <module> main(__file__) File "/Users/rwilliams/src/oss/mypy/.venv/lib/python3.5/site-packages/mypy_lang-0.2.0.dev0-py3.5.egg/mypy/main.py", line 91, in main type_check_only(sources, bin_dir, options) File "/Users/rwilliams/src/oss/mypy/.venv/lib/python3.5/site-packages/mypy_lang-0.2.0.dev0-py3.5.egg/mypy/main.py", line 134, in type_check_only python_path=options.python_path) File "/Users/rwilliams/src/oss/mypy/.venv/lib/python3.5/site-packages/mypy_lang-0.2.0.dev0-py3.5.egg/mypy/build.py", line 197, in build result = manager.process(initial_states) File "/Users/rwilliams/src/oss/mypy/.venv/lib/python3.5/site-packages/mypy_lang-0.2.0.dev0-py3.5.egg/mypy/build.py", line 383, in process next.process() File "/Users/rwilliams/src/oss/mypy/.venv/lib/python3.5/site-packages/mypy_lang-0.2.0.dev0-py3.5.egg/mypy/build.py", line 857, in process self.manager.reports.file(self.tree, type_map=self.manager.type_checker.type_map) File "/Users/rwilliams/src/oss/mypy/.venv/lib/python3.5/site-packages/mypy_lang-0.2.0.dev0-py3.5.egg/mypy/report.py", line 41, in file reporter.on_file(tree, type_map) File "/Users/rwilliams/src/oss/mypy/.venv/lib/python3.5/site-packages/mypy_lang-0.2.0.dev0-py3.5.egg/mypy/report.py", line 138, in on_file xml_pi = etree.ProcessingInstruction('xml', 'version="1.0" encoding="utf-8"') File "src/lxml/lxml.etree.pyx", line 3039, in lxml.etree.ProcessingInstruction (src/lxml/lxml.etree.c:81073) ValueError: Invalid PI name 'b'xml''
ValueError
def on_finish(self) -> None: import lxml.etree as etree self.last_xml = None # index_path = os.path.join(self.output_dir, 'index.xml') output_files = sorted(self.files, key=lambda x: x.module) root = etree.Element("mypy-report-index", name=self.main_file) doc = etree.ElementTree(root) for file_info in output_files: etree.SubElement( root, "file", file_info.attrib(), total=str(file_info.total()), name=file_info.name, module=file_info.module, ) xslt_path = os.path.relpath("mypy-html.xslt", ".") transform_pi = etree.ProcessingInstruction( "xml-stylesheet", 'type="text/xsl" href="%s"' % cgi.escape(xslt_path, True) ) root.addprevious(transform_pi) self.schema.assertValid(doc) self.last_xml = doc
def on_finish(self) -> None: import lxml.etree as etree self.last_xml = None # index_path = os.path.join(self.output_dir, 'index.xml') output_files = sorted(self.files, key=lambda x: x.module) root = etree.Element("mypy-report-index", name=self.main_file) doc = etree.ElementTree(root) for file_info in output_files: etree.SubElement( root, "file", file_info.attrib(), total=str(file_info.total()), name=file_info.name, module=file_info.module, ) xslt_path = os.path.relpath("mypy-html.xslt", ".") xml_pi = etree.ProcessingInstruction("xml", 'version="1.0" encoding="utf-8"') transform_pi = etree.ProcessingInstruction( "xml-stylesheet", 'type="text/xsl" href="%s"' % cgi.escape(xslt_path, True) ) root.addprevious(xml_pi) root.addprevious(transform_pi) self.schema.assertValid(doc) self.last_xml = doc
https://github.com/python/mypy/issues/1002
$ mypy --html-report mypy_dir defaultdict_example.py Traceback (most recent call last): File "/Users/rwilliams/src/oss/mypy/.venv/bin/mypy", line 6, in <module> main(__file__) File "/Users/rwilliams/src/oss/mypy/.venv/lib/python3.5/site-packages/mypy_lang-0.2.0.dev0-py3.5.egg/mypy/main.py", line 91, in main type_check_only(sources, bin_dir, options) File "/Users/rwilliams/src/oss/mypy/.venv/lib/python3.5/site-packages/mypy_lang-0.2.0.dev0-py3.5.egg/mypy/main.py", line 134, in type_check_only python_path=options.python_path) File "/Users/rwilliams/src/oss/mypy/.venv/lib/python3.5/site-packages/mypy_lang-0.2.0.dev0-py3.5.egg/mypy/build.py", line 197, in build result = manager.process(initial_states) File "/Users/rwilliams/src/oss/mypy/.venv/lib/python3.5/site-packages/mypy_lang-0.2.0.dev0-py3.5.egg/mypy/build.py", line 383, in process next.process() File "/Users/rwilliams/src/oss/mypy/.venv/lib/python3.5/site-packages/mypy_lang-0.2.0.dev0-py3.5.egg/mypy/build.py", line 857, in process self.manager.reports.file(self.tree, type_map=self.manager.type_checker.type_map) File "/Users/rwilliams/src/oss/mypy/.venv/lib/python3.5/site-packages/mypy_lang-0.2.0.dev0-py3.5.egg/mypy/report.py", line 41, in file reporter.on_file(tree, type_map) File "/Users/rwilliams/src/oss/mypy/.venv/lib/python3.5/site-packages/mypy_lang-0.2.0.dev0-py3.5.egg/mypy/report.py", line 138, in on_file xml_pi = etree.ProcessingInstruction('xml', 'version="1.0" encoding="utf-8"') File "src/lxml/lxml.etree.pyx", line 3039, in lxml.etree.ProcessingInstruction (src/lxml/lxml.etree.c:81073) ValueError: Invalid PI name 'b'xml''
ValueError
def check_argument_count( self, callee: CallableType, actual_types: List[Type], actual_kinds: List[int], actual_names: List[str], formal_to_actual: List[List[int]], context: Context, ) -> None: """Check that the number of arguments to a function are valid. Also check that there are no duplicate values for arguments. """ formal_kinds = callee.arg_kinds # Collect list of all actual arguments matched to formal arguments. all_actuals = [] # type: List[int] for actuals in formal_to_actual: all_actuals.extend(actuals) is_error = False # Keep track of errors to avoid duplicate errors. for i, kind in enumerate(actual_kinds): if i not in all_actuals and ( kind != nodes.ARG_STAR or not is_empty_tuple(actual_types[i]) ): # Extra actual: not matched by a formal argument. if kind != nodes.ARG_NAMED: self.msg.too_many_arguments(callee, context) else: self.msg.unexpected_keyword_argument(callee, actual_names[i], context) is_error = True elif kind == nodes.ARG_STAR and (nodes.ARG_STAR not in formal_kinds): actual_type = actual_types[i] if isinstance(actual_type, TupleType): if all_actuals.count(i) < len(actual_type.items): # Too many tuple items as some did not match. self.msg.too_many_arguments(callee, context) # *args can be applied even if the function takes a fixed # number of positional arguments. This may succeed at runtime. for i, kind in enumerate(formal_kinds): if kind == nodes.ARG_POS and (not formal_to_actual[i] and not is_error): # No actual for a mandatory positional formal. self.msg.too_few_arguments(callee, context, actual_names) elif kind in [ nodes.ARG_POS, nodes.ARG_OPT, nodes.ARG_NAMED, ] and is_duplicate_mapping(formal_to_actual[i], actual_kinds): if self.chk.typing_mode_full() or isinstance( actual_types[formal_to_actual[i][0]], TupleType ): self.msg.duplicate_argument_value(callee, i, context) elif ( kind == nodes.ARG_NAMED and formal_to_actual[i] and actual_kinds[formal_to_actual[i][0]] != nodes.ARG_NAMED ): # Positional argument when expecting a keyword argument. self.msg.too_many_positional_arguments(callee, context)
def check_argument_count( self, callee: CallableType, actual_types: List[Type], actual_kinds: List[int], actual_names: List[str], formal_to_actual: List[List[int]], context: Context, ) -> None: """Check that the number of arguments to a function are valid. Also check that there are no duplicate values for arguments. """ formal_kinds = callee.arg_kinds # Collect list of all actual arguments matched to formal arguments. all_actuals = [] # type: List[int] for actuals in formal_to_actual: all_actuals.extend(actuals) is_error = False # Keep track of errors to avoid duplicate errors. for i, kind in enumerate(actual_kinds): if i not in all_actuals and ( kind != nodes.ARG_STAR or not is_empty_tuple(actual_types[i]) ): # Extra actual: not matched by a formal argument. if kind != nodes.ARG_NAMED: self.msg.too_many_arguments(callee, context) else: self.msg.unexpected_keyword_argument(callee, actual_names[i], context) is_error = True elif kind == nodes.ARG_STAR and (nodes.ARG_STAR not in formal_kinds): actual_type = actual_types[i] if isinstance(actual_type, TupleType): if all_actuals.count(i) < len(actual_type.items): # Too many tuple items as some did not match. self.msg.too_many_arguments(callee, context) # *args can be applied even if the function takes a fixed # number of positional arguments. This may succeed at runtime. for i, kind in enumerate(formal_kinds): if kind == nodes.ARG_POS and (not formal_to_actual[i] and not is_error): # No actual for a mandatory positional formal. self.msg.too_few_arguments(callee, context, actual_names) elif kind in [ nodes.ARG_POS, nodes.ARG_OPT, nodes.ARG_NAMED, ] and is_duplicate_mapping(formal_to_actual[i], actual_kinds): if self.chk.typing_mode_full() or isinstance(actual_type, TupleType): self.msg.duplicate_argument_value(callee, i, context) elif ( kind == nodes.ARG_NAMED and formal_to_actual[i] and actual_kinds[formal_to_actual[i][0]] != nodes.ARG_NAMED ): # Positional argument when expecting a keyword argument. self.msg.too_many_positional_arguments(callee, context)
https://github.com/python/mypy/issues/1095
Traceback (most recent call last): File "/usr/bin/mypy", line 6, in <module> main(__file__) File "/usr/lib/python3.5/site-packages/mypy/main.py", line 50, in main type_check_only(sources, bin_dir, options) File "/usr/lib/python3.5/site-packages/mypy/main.py", line 93, in type_check_only python_path=options.python_path) File "/usr/lib/python3.5/site-packages/mypy/build.py", line 203, in build result = manager.process(initial_states) File "/usr/lib/python3.5/site-packages/mypy/build.py", line 385, in process next.process() File "/usr/lib/python3.5/site-packages/mypy/build.py", line 882, in process self.type_checker().visit_file(self.tree, self.tree.path) File "/usr/lib/python3.5/site-packages/mypy/checker.py", line 385, in visit_file self.accept(d) File "/usr/lib/python3.5/site-packages/mypy/checker.py", line 394, in accept typ = node.accept(self) File "/usr/lib/python3.5/site-packages/mypy/nodes.py", line 381, in accept return visitor.visit_func_def(self) File "/usr/lib/python3.5/site-packages/mypy/checker.py", line 449, in visit_func_def self.check_func_item(defn, name=defn.name()) File "/usr/lib/python3.5/site-packages/mypy/checker.py", line 484, in check_func_item self.check_func_def(defn, typ, name) File "/usr/lib/python3.5/site-packages/mypy/checker.py", line 567, in check_func_def self.accept_in_frame(item.body) File "/usr/lib/python3.5/site-packages/mypy/checker.py", line 409, in accept_in_frame answer = self.accept(node, type_context) File "/usr/lib/python3.5/site-packages/mypy/checker.py", line 394, in accept typ = node.accept(self) File "/usr/lib/python3.5/site-packages/mypy/nodes.py", line 525, in accept return visitor.visit_block(self) File "/usr/lib/python3.5/site-packages/mypy/checker.py", line 984, in visit_block self.accept(s) File "/usr/lib/python3.5/site-packages/mypy/checker.py", line 394, in accept typ = node.accept(self) File "/usr/lib/python3.5/site-packages/mypy/nodes.py", line 622, in accept return visitor.visit_return_stmt(self) File "/usr/lib/python3.5/site-packages/mypy/checker.py", line 1386, in visit_return_stmt typ = self.accept(s.expr, self.return_types[-1]) File "/usr/lib/python3.5/site-packages/mypy/checker.py", line 394, in accept typ = node.accept(self) File "/usr/lib/python3.5/site-packages/mypy/nodes.py", line 984, in accept return visitor.visit_call_expr(self) File "/usr/lib/python3.5/site-packages/mypy/checker.py", line 1841, in visit_call_expr return self.expr_checker.visit_call_expr(e) File "/usr/lib/python3.5/site-packages/mypy/checkexpr.py", line 126, in visit_call_expr return self.check_call_expr_with_callee_type(callee_type, e) File "/usr/lib/python3.5/site-packages/mypy/checkexpr.py", line 177, in check_call_expr_with_callee_type e.arg_names, callable_node=e.callee)[0] File "/usr/lib/python3.5/site-packages/mypy/checkexpr.py", line 224, in check_call arg_names, formal_to_actual, context) File "/usr/lib/python3.5/site-packages/mypy/checkexpr.py", line 535, in check_argument_count isinstance(actual_type, TupleType)): UnboundLocalError: local variable 'actual_type' referenced before assignment *** INTERNAL ERROR *** tmp.py:3: error: Internal error -- please report a bug at https://github.com/JukkaL/mypy/issues
UnboundLocalError
def analyze_typevar_declaration( self, t: Type ) -> Optional[List[Tuple[str, TypeVarExpr]]]: if not isinstance(t, UnboundType): return None unbound = cast(UnboundType, t) sym = self.lookup_qualified(unbound.name, unbound) if sym is None or sym.node is None: return None if sym.node.fullname() == "typing.Generic": tvars = [] # type: List[Tuple[str, TypeVarExpr]] for arg in unbound.args: tvar = self.analyze_unbound_tvar(arg) if tvar: tvars.append(tvar) else: self.fail("Free type variable expected in %s[...]" % sym.node.name(), t) return tvars return None
def analyze_typevar_declaration(self, t: Type) -> List[Tuple[str, TypeVarExpr]]: if not isinstance(t, UnboundType): return None unbound = cast(UnboundType, t) sym = self.lookup_qualified(unbound.name, unbound) if sym is None: return None if sym.node.fullname() == "typing.Generic": tvars = [] # type: List[Tuple[str, TypeVarExpr]] for arg in unbound.args: tvar = self.analyze_unbound_tvar(arg) if tvar: tvars.append(tvar) else: self.fail("Free type variable expected in %s[...]" % sym.node.name(), t) return tvars return None
https://github.com/python/mypy/issues/1029
Traceback (most recent call last): File "/Users/guido/src/mypy/scripts/mypy", line 6, in <module> main(__file__) File "/Users/guido/src/mypy/mypy/main.py", line 49, in main type_check_only(sources, bin_dir, options) File "/Users/guido/src/mypy/mypy/main.py", line 92, in type_check_only python_path=options.python_path) File "/Users/guido/src/mypy/mypy/build.py", line 197, in build result = manager.process(initial_states) File "/Users/guido/src/mypy/mypy/build.py", line 383, in process next.process() File "/Users/guido/src/mypy/mypy/build.py", line 823, in process self.semantic_analyzer().visit_file(self.tree, self.tree.path) File "/Users/guido/src/mypy/mypy/semanal.py", line 210, in visit_file d.accept(self) File "/Users/guido/src/mypy/mypy/nodes.py", line 483, in accept return visitor.visit_class_def(self) File "/Users/guido/src/mypy/mypy/semanal.py", line 460, in visit_class_def self.clean_up_bases_and_infer_type_variables(defn) File "/Users/guido/src/mypy/mypy/semanal.py", line 593, in clean_up_bases_and_infer_type_variables tvars = self.analyze_typevar_declaration(base) File "/Users/guido/src/mypy/mypy/semanal.py", line 615, in analyze_typevar_declaration if sym.node.fullname() == 'typing.Generic': AttributeError: 'NoneType' object has no attribute 'fullname'
AttributeError
def visit_instance(self, t: Instance) -> None: info = t.type # Check type argument count. if len(t.args) != len(info.type_vars): if len(t.args) == 0: # Insert implicit 'Any' type arguments. t.args = [AnyType()] * len(info.type_vars) return # Invalid number of type parameters. n = len(info.type_vars) s = "{} type arguments".format(n) if n == 0: s = "no type arguments" elif n == 1: s = "1 type argument" act = str(len(t.args)) if act == "0": act = "none" self.fail('"{}" expects {}, but {} given'.format(info.name(), s, act), t) # Construct the correct number of type arguments, as # otherwise the type checker may crash as it expects # things to be right. t.args = [AnyType() for _ in info.type_vars] elif info.defn.type_vars: # Check type argument values. for arg, TypeVar in zip(t.args, info.defn.type_vars): if TypeVar.values: if isinstance(arg, TypeVarType): arg_values = arg.values if not arg_values: self.fail( 'Type variable "{}" not valid as type ' 'argument value for "{}"'.format(arg.name, info.name()), t, ) continue else: arg_values = [arg] self.check_type_var_values(info, arg_values, TypeVar.values, t) for arg in t.args: arg.accept(self)
def visit_instance(self, t: Instance) -> None: info = t.type # Check type argument count. if len(t.args) != len(info.type_vars): if len(t.args) == 0: # Insert implicit 'Any' type arguments. t.args = [AnyType()] * len(info.type_vars) return # Invalid number of type parameters. n = len(info.type_vars) s = "{} type arguments".format(n) if n == 0: s = "no type arguments" elif n == 1: s = "1 type argument" act = str(len(t.args)) if act == "0": act = "none" self.fail('"{}" expects {}, but {} given'.format(info.name(), s, act), t) elif info.defn.type_vars: # Check type argument values. for arg, TypeVar in zip(t.args, info.defn.type_vars): if TypeVar.values: if isinstance(arg, TypeVarType): arg_values = arg.values if not arg_values: self.fail( 'Type variable "{}" not valid as type ' 'argument value for "{}"'.format(arg.name, info.name()), t, ) continue else: arg_values = [arg] self.check_type_var_values(info, arg_values, TypeVar.values, t) for arg in t.args: arg.accept(self)
https://github.com/python/mypy/issues/996
Traceback (most recent call last): ... cb = infer_constraints(mapped.args[i], instance.args[i], IndexError: list index out of range
IndexError
def analyze_class_attribute_access( itype: Instance, name: str, context: Context, is_lvalue: bool, builtin_type: Callable[[str], Instance], msg: MessageBuilder, ) -> Type: node = itype.type.get(name) if not node: if itype.type.fallback_to_any: return AnyType() return None is_decorated = isinstance(node.node, Decorator) is_method = is_decorated or isinstance(node.node, FuncDef) if is_lvalue: if is_method: msg.cant_assign_to_method(context) if isinstance(node.node, TypeInfo): msg.fail(messages.CANNOT_ASSIGN_TO_TYPE, context) if itype.type.is_enum and not (is_lvalue or is_decorated or is_method): return itype t = node.type if t: is_classmethod = is_decorated and cast(Decorator, node.node).func.is_class return add_class_tvars(t, itype.type, is_classmethod, builtin_type) elif isinstance(node.node, Var): msg.cannot_determine_type(name, context) return AnyType() if isinstance(node.node, TypeInfo): return type_object_type(cast(TypeInfo, node.node), builtin_type) if is_decorated: # TODO: Return type of decorated function. This is quick hack to work around #998. return AnyType() else: return function_type( cast(FuncBase, node.node), builtin_type("builtins.function") )
def analyze_class_attribute_access( itype: Instance, name: str, context: Context, is_lvalue: bool, builtin_type: Callable[[str], Instance], msg: MessageBuilder, ) -> Type: node = itype.type.get(name) if not node: if itype.type.fallback_to_any: return AnyType() return None is_decorated = isinstance(node.node, Decorator) is_method = is_decorated or isinstance(node.node, FuncDef) if is_lvalue: if is_method: msg.cant_assign_to_method(context) if isinstance(node.node, TypeInfo): msg.fail(messages.CANNOT_ASSIGN_TO_TYPE, context) if itype.type.is_enum and not (is_lvalue or is_decorated or is_method): return itype t = node.type if t: is_classmethod = is_decorated and cast(Decorator, node.node).func.is_class return add_class_tvars(t, itype.type, is_classmethod, builtin_type) elif isinstance(node.node, Var): msg.cannot_determine_type(name, context) return AnyType() if isinstance(node.node, TypeInfo): return type_object_type(cast(TypeInfo, node.node), builtin_type) return function_type(cast(FuncBase, node.node), builtin_type("builtins.function"))
https://github.com/python/mypy/issues/998
Traceback (most recent call last): File "/Users/guido/src/mypy/scripts/mypy", line 6, in <module> main(__file__) File "/Users/guido/src/mypy/mypy/main.py", line 49, in main type_check_only(sources, bin_dir, options) File "/Users/guido/src/mypy/mypy/main.py", line 92, in type_check_only python_path=options.python_path) File "/Users/guido/src/mypy/mypy/build.py", line 197, in build result = manager.process(initial_states) File "/Users/guido/src/mypy/mypy/build.py", line 379, in process next.process() File "/Users/guido/src/mypy/mypy/build.py", line 849, in process self.type_checker().visit_file(self.tree, self.tree.path) File "/Users/guido/src/mypy/mypy/checker.py", line 371, in visit_file self.accept(d) File "/Users/guido/src/mypy/mypy/checker.py", line 379, in accept typ = node.accept(self) File "/Users/guido/src/mypy/mypy/nodes.py", line 552, in accept return visitor.visit_assignment_stmt(self) File "/Users/guido/src/mypy/mypy/checker.py", line 953, in visit_assignment_stmt self.check_assignment(s.lvalues[-1], s.rvalue, s.type is None) File "/Users/guido/src/mypy/mypy/checker.py", line 981, in check_assignment self.infer_variable_type(inferred, lvalue, self.accept(rvalue), File "/Users/guido/src/mypy/mypy/checker.py", line 379, in accept typ = node.accept(self) File "/Users/guido/src/mypy/mypy/nodes.py", line 929, in accept return visitor.visit_member_expr(self) File "/Users/guido/src/mypy/mypy/checker.py", line 1770, in visit_member_expr return self.expr_checker.visit_member_expr(e) File "/Users/guido/src/mypy/mypy/checkexpr.py", line 680, in visit_member_expr result = self.analyze_ordinary_member_access(e, False) File "/Users/guido/src/mypy/mypy/checkexpr.py", line 693, in analyze_ordinary_member_access self.named_type, self.msg) File "/Users/guido/src/mypy/mypy/checkmember.py", line 84, in analyze_member_access result = analyze_class_attribute_access(itype, name, node, is_lvalue, builtin_type, msg) File "/Users/guido/src/mypy/mypy/checkmember.py", line 240, in analyze_class_attribute_access return function_type(cast(FuncBase, node.node), builtin_type('builtins.function')) File "/Users/guido/src/mypy/mypy/nodes.py", line 1733, in function_type if func.type: AttributeError: 'Decorator' object has no attribute 'type' *** INTERNAL ERROR *** ui/common/uikit.py:64: error: Internal error -- please report a bug at https://github.com/JukkaL/mypy/issues
AttributeError
def check_compatibility( self, name: str, base1: TypeInfo, base2: TypeInfo, ctx: Context ) -> None: """Check if attribute name in base1 is compatible with base2 in multiple inheritance. Assume base1 comes before base2 in the MRO, and that base1 and base2 don't have a direct subclass relationship (i.e., the compatibility requirement only derives from multiple inheritance). """ if name == "__init__": # __init__ can be incompatible -- it's a special case. return first = base1[name] second = base2[name] first_type = first.type if first_type is None and isinstance(first.node, FuncDef): first_type = self.function_type(cast(FuncDef, first.node)) second_type = second.type if second_type is None and isinstance(second.node, FuncDef): second_type = self.function_type(cast(FuncDef, second.node)) # TODO: What if some classes are generic? if isinstance(first_type, FunctionLike) and isinstance(second_type, FunctionLike): # Method override first_sig = method_type(cast(FunctionLike, first_type)) second_sig = method_type(cast(FunctionLike, second_type)) ok = is_subtype(first_sig, second_sig) elif first_type and second_type: ok = is_equivalent(first_type, second_type) else: if first_type is None: self.msg.cannot_determine_type_in_base(name, base1.name(), ctx) if second_type is None: self.msg.cannot_determine_type_in_base(name, base2.name(), ctx) ok = True if not ok: self.msg.base_class_definitions_incompatible(name, base1, base2, ctx)
def check_compatibility( self, name: str, base1: TypeInfo, base2: TypeInfo, ctx: Context ) -> None: """Check if attribute name in base1 is compatible with base2 in multiple inheritance. Assume base1 comes before base2 in the MRO, and that base1 and base2 don't have a direct subclass relationship (i.e., the compatibility requirement only derives from multiple inheritance). """ if name == "__init__": # __init__ can be incompatible -- it's a special case. return first = base1[name] second = base2[name] first_type = first.type if first_type is None and isinstance(first.node, FuncDef): first_type = self.function_type(cast(FuncDef, first.node)) second_type = second.type if second_type is None and isinstance(second.node, FuncDef): second_type = self.function_type(cast(FuncDef, second.node)) # TODO: What if first_type or second_type is None? What if some classes are generic? if isinstance(first_type, FunctionLike) and isinstance(second_type, FunctionLike): # Method override first_sig = method_type(cast(FunctionLike, first_type)) second_sig = method_type(cast(FunctionLike, second_type)) ok = is_subtype(first_sig, second_sig) else: ok = is_equivalent(first_type, second_type) if not ok: self.msg.base_class_definitions_incompatible(name, base1, base2, ctx)
https://github.com/python/mypy/issues/998
Traceback (most recent call last): File "/Users/guido/src/mypy/scripts/mypy", line 6, in <module> main(__file__) File "/Users/guido/src/mypy/mypy/main.py", line 49, in main type_check_only(sources, bin_dir, options) File "/Users/guido/src/mypy/mypy/main.py", line 92, in type_check_only python_path=options.python_path) File "/Users/guido/src/mypy/mypy/build.py", line 197, in build result = manager.process(initial_states) File "/Users/guido/src/mypy/mypy/build.py", line 379, in process next.process() File "/Users/guido/src/mypy/mypy/build.py", line 849, in process self.type_checker().visit_file(self.tree, self.tree.path) File "/Users/guido/src/mypy/mypy/checker.py", line 371, in visit_file self.accept(d) File "/Users/guido/src/mypy/mypy/checker.py", line 379, in accept typ = node.accept(self) File "/Users/guido/src/mypy/mypy/nodes.py", line 552, in accept return visitor.visit_assignment_stmt(self) File "/Users/guido/src/mypy/mypy/checker.py", line 953, in visit_assignment_stmt self.check_assignment(s.lvalues[-1], s.rvalue, s.type is None) File "/Users/guido/src/mypy/mypy/checker.py", line 981, in check_assignment self.infer_variable_type(inferred, lvalue, self.accept(rvalue), File "/Users/guido/src/mypy/mypy/checker.py", line 379, in accept typ = node.accept(self) File "/Users/guido/src/mypy/mypy/nodes.py", line 929, in accept return visitor.visit_member_expr(self) File "/Users/guido/src/mypy/mypy/checker.py", line 1770, in visit_member_expr return self.expr_checker.visit_member_expr(e) File "/Users/guido/src/mypy/mypy/checkexpr.py", line 680, in visit_member_expr result = self.analyze_ordinary_member_access(e, False) File "/Users/guido/src/mypy/mypy/checkexpr.py", line 693, in analyze_ordinary_member_access self.named_type, self.msg) File "/Users/guido/src/mypy/mypy/checkmember.py", line 84, in analyze_member_access result = analyze_class_attribute_access(itype, name, node, is_lvalue, builtin_type, msg) File "/Users/guido/src/mypy/mypy/checkmember.py", line 240, in analyze_class_attribute_access return function_type(cast(FuncBase, node.node), builtin_type('builtins.function')) File "/Users/guido/src/mypy/mypy/nodes.py", line 1733, in function_type if func.type: AttributeError: 'Decorator' object has no attribute 'type' *** INTERNAL ERROR *** ui/common/uikit.py:64: error: Internal error -- please report a bug at https://github.com/JukkaL/mypy/issues
AttributeError
def visit_type_var(self, template: TypeVarType) -> List[Constraint]: if self.actual: return [Constraint(template.id, self.direction, self.actual)] else: return []
def visit_type_var(self, template: TypeVarType) -> List[Constraint]: return [Constraint(template.id, self.direction, self.actual)]
https://github.com/python/mypy/issues/674
Traceback (most recent call last): File "scripts/mypy", line 182, in <module> main() File "scripts/mypy", line 36, in main type_check_only(path, module, bin_dir, options) File "scripts/mypy", line 80, in type_check_only python_path=options.python_path) File "/home/jukka/project/mypy/mypy/build.py", line 164, in build result = manager.process(UnprocessedFile(info, program_text)) File "/home/jukka/project/mypy/mypy/build.py", line 341, in process next.process() File "/home/jukka/project/mypy/mypy/build.py", line 814, in process self.type_checker().visit_file(self.tree, self.tree.path) File "/home/jukka/project/mypy/mypy/checker.py", line 350, in visit_file self.accept(d) File "/home/jukka/project/mypy/mypy/checker.py", line 357, in accept typ = node.accept(self) File "/home/jukka/project/mypy/mypy/nodes.py", line 519, in accept return visitor.visit_expression_stmt(self) File "/home/jukka/project/mypy/mypy/checker.py", line 1302, in visit_expression_stmt self.accept(s.expr) File "/home/jukka/project/mypy/mypy/checker.py", line 357, in accept typ = node.accept(self) File "/home/jukka/project/mypy/mypy/nodes.py", line 938, in accept return visitor.visit_call_expr(self) File "/home/jukka/project/mypy/mypy/checker.py", line 1709, in visit_call_expr result = self.expr_checker.visit_call_expr(e) File "/home/jukka/project/mypy/mypy/checkexpr.py", line 118, in visit_call_expr return self.check_call_expr_with_callee_type(callee_type, e) File "/home/jukka/project/mypy/mypy/checkexpr.py", line 128, in check_call_expr_with_callee_type e.arg_names, callable_node=e.callee)[0] File "/home/jukka/project/mypy/mypy/checkexpr.py", line 171, in check_call callee, args, arg_kinds, formal_to_actual, context) File "/home/jukka/project/mypy/mypy/checkexpr.py", line 351, in infer_function_type_arguments callee_type, pass1_args, arg_kinds, formal_to_actual) # type: List[Type] File "/home/jukka/project/mypy/mypy/infer.py", line 33, in infer_function_type_arguments return solve_constraints(type_vars, constraints) File "/home/jukka/project/mypy/mypy/solve.py", line 41, in solve_constraints bottom = join_types(bottom, c.target) File "/home/jukka/project/mypy/mypy/join.py", line 68, in join_types return t.accept(TypeJoinVisitor(s)) AttributeError: 'NoneType' object has no attribute 'accept'
AttributeError
def create_cloned_field( field: ModelField, *, cloned_types: Dict[Type[BaseModel], Type[BaseModel]] = None, ) -> ModelField: # _cloned_types has already cloned types, to support recursive models if cloned_types is None: cloned_types = dict() original_type = field.type_ if is_dataclass(original_type) and hasattr(original_type, "__pydantic_model__"): original_type = original_type.__pydantic_model__ # type: ignore use_type = original_type if lenient_issubclass(original_type, BaseModel): original_type = cast(Type[BaseModel], original_type) use_type = cloned_types.get(original_type) if use_type is None: use_type = create_model(original_type.__name__, __base__=original_type) cloned_types[original_type] = use_type for f in original_type.__fields__.values(): use_type.__fields__[f.name] = create_cloned_field( f, cloned_types=cloned_types ) new_field = create_response_field(name=field.name, type_=use_type) new_field.has_alias = field.has_alias new_field.alias = field.alias new_field.class_validators = field.class_validators new_field.default = field.default new_field.required = field.required new_field.model_config = field.model_config if PYDANTIC_1: new_field.field_info = field.field_info else: # pragma: nocover new_field.schema = field.schema # type: ignore new_field.allow_none = field.allow_none new_field.validate_always = field.validate_always if field.sub_fields: new_field.sub_fields = [ create_cloned_field(sub_field, cloned_types=cloned_types) for sub_field in field.sub_fields ] if field.key_field: new_field.key_field = create_cloned_field( field.key_field, cloned_types=cloned_types ) new_field.validators = field.validators if PYDANTIC_1: new_field.pre_validators = field.pre_validators new_field.post_validators = field.post_validators else: # pragma: nocover new_field.whole_pre_validators = field.whole_pre_validators # type: ignore new_field.whole_post_validators = field.whole_post_validators # type: ignore new_field.parse_json = field.parse_json new_field.shape = field.shape try: new_field.populate_validators() except AttributeError: # pragma: nocover # TODO: remove when removing support for Pydantic < 1.0.0 new_field._populate_validators() # type: ignore return new_field
def create_cloned_field(field: ModelField) -> ModelField: original_type = field.type_ if is_dataclass(original_type) and hasattr(original_type, "__pydantic_model__"): original_type = original_type.__pydantic_model__ # type: ignore use_type = original_type if lenient_issubclass(original_type, BaseModel): original_type = cast(Type[BaseModel], original_type) use_type = create_model(original_type.__name__, __base__=original_type) for f in original_type.__fields__.values(): use_type.__fields__[f.name] = create_cloned_field(f) new_field = create_response_field(name=field.name, type_=use_type) new_field.has_alias = field.has_alias new_field.alias = field.alias new_field.class_validators = field.class_validators new_field.default = field.default new_field.required = field.required new_field.model_config = field.model_config if PYDANTIC_1: new_field.field_info = field.field_info else: # pragma: nocover new_field.schema = field.schema # type: ignore new_field.allow_none = field.allow_none new_field.validate_always = field.validate_always if field.sub_fields: new_field.sub_fields = [ create_cloned_field(sub_field) for sub_field in field.sub_fields ] if field.key_field: new_field.key_field = create_cloned_field(field.key_field) new_field.validators = field.validators if PYDANTIC_1: new_field.pre_validators = field.pre_validators new_field.post_validators = field.post_validators else: # pragma: nocover new_field.whole_pre_validators = field.whole_pre_validators # type: ignore new_field.whole_post_validators = field.whole_post_validators # type: ignore new_field.parse_json = field.parse_json new_field.shape = field.shape try: new_field.populate_validators() except AttributeError: # pragma: nocover # TODO: remove when removing support for Pydantic < 1.0.0 new_field._populate_validators() # type: ignore return new_field
https://github.com/tiangolo/fastapi/issues/894
Traceback (most recent call last): File "test.py", line 21, in <module> @app.get('/group/{group_id}', response_model=Group) File "D:\virtualenvs\test\lib\site-packages\fastapi\routing.py", line 494, in decorator callbacks=callbacks, File "D:\virtualenvs\test\lib\site-packages\fastapi\routing.py", line 438, in add_api_route callbacks=callbacks, File "D:\virtualenvs\test\lib\site-packages\fastapi\routing.py", line 275, in __init__ ] = create_cloned_field(self.response_field) File "D:\virtualenvs\test\lib\site-packages\fastapi\utils.py", line 100, in create_cloned_field use_type.__fields__[f.name] = create_cloned_field(f) File "D:\virtualenvs\test\lib\site-packages\fastapi\utils.py", line 100, in create_cloned_field use_type.__fields__[f.name] = create_cloned_field(f) File "D:\virtualenvs\test\lib\site-packages\fastapi\utils.py", line 100, in create_cloned_field use_type.__fields__[f.name] = create_cloned_field(f) [Previous line repeated 981 more times] File "D:\virtualenvs\test\lib\site-packages\fastapi\utils.py", line 97, in create_cloned_field original_type.__name__, __config__=original_type.__config__ File "D:\virtualenvs\test\lib\site-packages\pydantic\main.py", line 773, in create_model return type(model_name, (__base__,), namespace) File "D:\virtualenvs\test\lib\site-packages\pydantic\main.py", line 152, in __new__ if issubclass(base, BaseModel) and base != BaseModel: File "D:\virtualenvs\test\lib\abc.py", line 143, in __subclasscheck__ return _abc_subclasscheck(cls, subclass) RecursionError: maximum recursion depth exceeded in comparison
RecursionError
async def request_body_to_args( required_params: List[ModelField], received_body: Optional[Union[Dict[str, Any], FormData]], ) -> Tuple[Dict[str, Any], List[ErrorWrapper]]: values = {} errors = [] if required_params: field = required_params[0] field_info = get_field_info(field) embed = getattr(field_info, "embed", None) if len(required_params) == 1 and not embed: received_body = {field.alias: received_body} for field in required_params: value: Any = None if received_body is not None: if ( field.shape in sequence_shapes or field.type_ in sequence_types ) and isinstance(received_body, FormData): value = received_body.getlist(field.alias) else: try: value = received_body.get(field.alias) except AttributeError: errors.append(get_missing_field_error(field.alias)) continue if ( value is None or (isinstance(field_info, params.Form) and value == "") or ( isinstance(field_info, params.Form) and field.shape in sequence_shapes and len(value) == 0 ) ): if field.required: errors.append(get_missing_field_error(field.alias)) else: values[field.name] = deepcopy(field.default) continue if ( isinstance(field_info, params.File) and lenient_issubclass(field.type_, bytes) and isinstance(value, UploadFile) ): value = await value.read() elif ( field.shape in sequence_shapes and isinstance(field_info, params.File) and lenient_issubclass(field.type_, bytes) and isinstance(value, sequence_types) ): awaitables = [sub_value.read() for sub_value in value] contents = await asyncio.gather(*awaitables) value = sequence_shape_to_type[field.shape](contents) v_, errors_ = field.validate(value, values, loc=("body", field.alias)) if isinstance(errors_, ErrorWrapper): errors.append(errors_) elif isinstance(errors_, list): errors.extend(errors_) else: values[field.name] = v_ return values, errors
async def request_body_to_args( required_params: List[ModelField], received_body: Optional[Union[Dict[str, Any], FormData]], ) -> Tuple[Dict[str, Any], List[ErrorWrapper]]: values = {} errors = [] if required_params: field = required_params[0] field_info = get_field_info(field) embed = getattr(field_info, "embed", None) if len(required_params) == 1 and not embed: received_body = {field.alias: received_body} for field in required_params: value: Any = None if received_body is not None: if ( field.shape in sequence_shapes or field.type_ in sequence_types ) and isinstance(received_body, FormData): value = received_body.getlist(field.alias) else: value = received_body.get(field.alias) if ( value is None or (isinstance(field_info, params.Form) and value == "") or ( isinstance(field_info, params.Form) and field.shape in sequence_shapes and len(value) == 0 ) ): if field.required: if PYDANTIC_1: errors.append( ErrorWrapper(MissingError(), loc=("body", field.alias)) ) else: # pragma: nocover errors.append( ErrorWrapper( # type: ignore MissingError(), loc=("body", field.alias), config=BaseConfig, ) ) else: values[field.name] = deepcopy(field.default) continue if ( isinstance(field_info, params.File) and lenient_issubclass(field.type_, bytes) and isinstance(value, UploadFile) ): value = await value.read() elif ( field.shape in sequence_shapes and isinstance(field_info, params.File) and lenient_issubclass(field.type_, bytes) and isinstance(value, sequence_types) ): awaitables = [sub_value.read() for sub_value in value] contents = await asyncio.gather(*awaitables) value = sequence_shape_to_type[field.shape](contents) v_, errors_ = field.validate(value, values, loc=("body", field.alias)) if isinstance(errors_, ErrorWrapper): errors.append(errors_) elif isinstance(errors_, list): errors.extend(errors_) else: values[field.name] = v_ return values, errors
https://github.com/tiangolo/fastapi/issues/914
INFO: 127.0.0.1:60652 - "POST /test/ HTTP/1.1" 500 Internal Server Error ERROR: Exception in ASGI application Traceback (most recent call last): File "/test/venv38/lib/python3.8/site-packages/uvicorn/protocols/http/httptools_impl.py", line 385, in run_asgi result = await app(self.scope, self.receive, self.send) File "/test/venv38/lib/python3.8/site-packages/uvicorn/middleware/proxy_headers.py", line 45, in __call__ return await self.app(scope, receive, send) File "/test/venv38/lib/python3.8/site-packages/fastapi/applications.py", line 140, in __call__ await super().__call__(scope, receive, send) File "/test/venv38/lib/python3.8/site-packages/starlette/applications.py", line 134, in __call__ await self.error_middleware(scope, receive, send) File "/test/venv38/lib/python3.8/site-packages/starlette/middleware/errors.py", line 178, in __call__ raise exc from None File "/test/venv38/lib/python3.8/site-packages/starlette/middleware/errors.py", line 156, in __call__ await self.app(scope, receive, _send) File "/test/venv38/lib/python3.8/site-packages/starlette/exceptions.py", line 73, in __call__ raise exc from None File "/test/venv38/lib/python3.8/site-packages/starlette/exceptions.py", line 62, in __call__ await self.app(scope, receive, sender) File "/test/venv38/lib/python3.8/site-packages/starlette/routing.py", line 590, in __call__ await route(scope, receive, send) File "/test/venv38/lib/python3.8/site-packages/starlette/routing.py", line 208, in __call__ await self.app(scope, receive, send) File "/test/venv38/lib/python3.8/site-packages/starlette/routing.py", line 41, in app response = await func(request) File "/test/venv38/lib/python3.8/site-packages/fastapi/routing.py", line 115, in app solved_result = await solve_dependencies( File "/test/venv38/lib/python3.8/site-packages/fastapi/dependencies/utils.py", line 547, in solve_dependencies ) = await request_body_to_args( # body_params checked above File "/test/venv38/lib/python3.8/site-packages/fastapi/dependencies/utils.py", line 637, in request_body_to_args value = received_body.get(field.alias) AttributeError: 'list' object has no attribute 'get'
AttributeError
def generate_operation_id(*, route: routing.APIRoute, method: str) -> str: if route.operation_id: return route.operation_id path: str = route.path_format return generate_operation_id_for_path(name=route.name, path=path, method=method)
def generate_operation_id(*, route: routing.APIRoute, method: str) -> str: if route.operation_id: return route.operation_id path: str = route.path_format operation_id = route.name + path operation_id = operation_id.replace("{", "_").replace("}", "_").replace("/", "_") operation_id = operation_id + "_" + method.lower() return operation_id
https://github.com/tiangolo/fastapi/issues/284
ip-10-8-0-198% % uvicorn run:app --reload INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit) INFO: Started reloader process [77186] WARNING:root:email-validator not installed, email fields will be treated as str. To install, run: pip install email-validator INFO:uvicorn:Started server process [77188] INFO:uvicorn:Waiting for application startup. INFO:uvicorn:('127.0.0.1', 54932) - "GET /docs HTTP/1.1" 200 INFO:uvicorn:('127.0.0.1', 54932) - "GET /openapi.json HTTP/1.1" 500 ERROR:uvicorn:Exception in ASGI application Traceback (most recent call last): File "/Users/edwardbanner/.anaconda/lib/python3.6/site-packages/uvicorn/protocols/http/httptools_impl.py", line 368, in run_asgi result = await app(self.scope, self.receive, self.send) File "/Users/edwardbanner/.anaconda/lib/python3.6/site-packages/uvicorn/middleware/asgi2.py", line 7, in __call__ await instance(receive, send) File "/Users/edwardbanner/.anaconda/lib/python3.6/site-packages/starlette/middleware/errors.py", line 125, in asgi raise exc from None File "/Users/edwardbanner/.anaconda/lib/python3.6/site-packages/starlette/middleware/errors.py", line 103, in asgi await asgi(receive, _send) File "/Users/edwardbanner/.anaconda/lib/python3.6/site-packages/starlette/exceptions.py", line 74, in app raise exc from None File "/Users/edwardbanner/.anaconda/lib/python3.6/site-packages/starlette/exceptions.py", line 63, in app await instance(receive, sender) File "/Users/edwardbanner/.anaconda/lib/python3.6/site-packages/starlette/routing.py", line 43, in awaitable response = await run_in_threadpool(func, request) File "/Users/edwardbanner/.anaconda/lib/python3.6/site-packages/starlette/concurrency.py", line 24, in run_in_threadpool return await loop.run_in_executor(None, func, *args) File "/Users/edwardbanner/.anaconda/lib/python3.6/concurrent/futures/thread.py", line 56, in run result = self.fn(*self.args, **self.kwargs) File "/Users/edwardbanner/.anaconda/lib/python3.6/site-packages/fastapi/applications.py", line 83, in <lambda> lambda req: JSONResponse(self.openapi()), File "/Users/edwardbanner/.anaconda/lib/python3.6/site-packages/fastapi/applications.py", line 75, in openapi openapi_prefix=self.openapi_prefix, File "/Users/edwardbanner/.anaconda/lib/python3.6/site-packages/fastapi/openapi/utils.py", line 248, in get_openapi flat_models=flat_models, model_name_map=model_name_map File "/Users/edwardbanner/.anaconda/lib/python3.6/site-packages/fastapi/utils.py", line 45, in get_model_definitions model_name = model_name_map[model] KeyError: <class 'Body_compute'>
KeyError
def __init__( self, path: str, endpoint: Callable, *, response_model: Type[Any] = None, status_code: int = 200, tags: List[str] = None, dependencies: Sequence[params.Depends] = None, summary: str = None, description: str = None, response_description: str = "Successful Response", responses: Dict[Union[int, str], Dict[str, Any]] = None, deprecated: bool = None, name: str = None, methods: Optional[Union[Set[str], List[str]]] = None, operation_id: str = None, response_model_include: Set[str] = None, response_model_exclude: Set[str] = set(), response_model_by_alias: bool = True, response_model_skip_defaults: bool = False, include_in_schema: bool = True, response_class: Type[Response] = JSONResponse, dependency_overrides_provider: Any = None, ) -> None: assert path.startswith("/"), "Routed paths must always start with '/'" self.path = path self.endpoint = endpoint self.name = get_name(endpoint) if name is None else name self.path_regex, self.path_format, self.param_convertors = compile_path(path) if methods is None: methods = ["GET"] self.methods = set([method.upper() for method in methods]) self.unique_id = generate_operation_id_for_path( name=self.name, path=self.path_format, method=list(methods)[0] ) self.response_model = response_model if self.response_model: assert lenient_issubclass(response_class, JSONResponse), ( "To declare a type the response must be a JSON response" ) response_name = "Response_" + self.unique_id self.response_field: Optional[Field] = Field( name=response_name, type_=self.response_model, class_validators={}, default=None, required=False, model_config=BaseConfig, schema=Schema(None), ) # Create a clone of the field, so that a Pydantic submodel is not returned # as is just because it's an instance of a subclass of a more limited class # e.g. UserInDB (containing hashed_password) could be a subclass of User # that doesn't have the hashed_password. But because it's a subclass, it # would pass the validation and be returned as is. # By being a new field, no inheritance will be passed as is. A new model # will be always created. self.secure_cloned_response_field: Optional[Field] = create_cloned_field( self.response_field ) else: self.response_field = None self.secure_cloned_response_field = None self.status_code = status_code self.tags = tags or [] if dependencies: self.dependencies = list(dependencies) else: self.dependencies = [] self.summary = summary self.description = description or inspect.cleandoc(self.endpoint.__doc__ or "") self.response_description = response_description self.responses = responses or {} response_fields = {} for additional_status_code, response in self.responses.items(): assert isinstance(response, dict), "An additional response must be a dict" model = response.get("model") if model: assert lenient_issubclass(model, BaseModel), ( "A response model must be a Pydantic model" ) response_name = f"Response_{additional_status_code}_{self.unique_id}" response_field = Field( name=response_name, type_=model, class_validators=None, default=None, required=False, model_config=BaseConfig, schema=Schema(None), ) response_fields[additional_status_code] = response_field if response_fields: self.response_fields: Dict[Union[int, str], Field] = response_fields else: self.response_fields = {} self.deprecated = deprecated self.operation_id = operation_id self.response_model_include = response_model_include self.response_model_exclude = response_model_exclude self.response_model_by_alias = response_model_by_alias self.response_model_skip_defaults = response_model_skip_defaults self.include_in_schema = include_in_schema self.response_class = response_class assert inspect.isfunction(endpoint) or inspect.ismethod(endpoint), ( f"An endpoint must be a function or method" ) self.dependant = get_dependant(path=self.path_format, call=self.endpoint) for depends in self.dependencies[::-1]: self.dependant.dependencies.insert( 0, get_parameterless_sub_dependant(depends=depends, path=self.path_format), ) self.body_field = get_body_field(dependant=self.dependant, name=self.unique_id) self.dependency_overrides_provider = dependency_overrides_provider self.app = request_response( get_app( dependant=self.dependant, body_field=self.body_field, status_code=self.status_code, response_class=self.response_class, response_field=self.secure_cloned_response_field, response_model_include=self.response_model_include, response_model_exclude=self.response_model_exclude, response_model_by_alias=self.response_model_by_alias, response_model_skip_defaults=self.response_model_skip_defaults, dependency_overrides_provider=self.dependency_overrides_provider, ) )
def __init__( self, path: str, endpoint: Callable, *, response_model: Type[Any] = None, status_code: int = 200, tags: List[str] = None, dependencies: Sequence[params.Depends] = None, summary: str = None, description: str = None, response_description: str = "Successful Response", responses: Dict[Union[int, str], Dict[str, Any]] = None, deprecated: bool = None, name: str = None, methods: Optional[Union[Set[str], List[str]]] = None, operation_id: str = None, response_model_include: Set[str] = None, response_model_exclude: Set[str] = set(), response_model_by_alias: bool = True, response_model_skip_defaults: bool = False, include_in_schema: bool = True, response_class: Type[Response] = JSONResponse, dependency_overrides_provider: Any = None, ) -> None: assert path.startswith("/"), "Routed paths must always start with '/'" self.path = path self.endpoint = endpoint self.name = get_name(endpoint) if name is None else name self.response_model = response_model if self.response_model: assert lenient_issubclass(response_class, JSONResponse), ( "To declare a type the response must be a JSON response" ) response_name = "Response_" + self.name self.response_field: Optional[Field] = Field( name=response_name, type_=self.response_model, class_validators={}, default=None, required=False, model_config=BaseConfig, schema=Schema(None), ) # Create a clone of the field, so that a Pydantic submodel is not returned # as is just because it's an instance of a subclass of a more limited class # e.g. UserInDB (containing hashed_password) could be a subclass of User # that doesn't have the hashed_password. But because it's a subclass, it # would pass the validation and be returned as is. # By being a new field, no inheritance will be passed as is. A new model # will be always created. self.secure_cloned_response_field: Optional[Field] = create_cloned_field( self.response_field ) else: self.response_field = None self.secure_cloned_response_field = None self.status_code = status_code self.tags = tags or [] if dependencies: self.dependencies = list(dependencies) else: self.dependencies = [] self.summary = summary self.description = description or inspect.cleandoc(self.endpoint.__doc__ or "") self.response_description = response_description self.responses = responses or {} response_fields = {} for additional_status_code, response in self.responses.items(): assert isinstance(response, dict), "An additional response must be a dict" model = response.get("model") if model: assert lenient_issubclass(model, BaseModel), ( "A response model must be a Pydantic model" ) response_name = f"Response_{additional_status_code}_{self.name}" response_field = Field( name=response_name, type_=model, class_validators=None, default=None, required=False, model_config=BaseConfig, schema=Schema(None), ) response_fields[additional_status_code] = response_field if response_fields: self.response_fields: Dict[Union[int, str], Field] = response_fields else: self.response_fields = {} self.deprecated = deprecated if methods is None: methods = ["GET"] self.methods = set([method.upper() for method in methods]) self.operation_id = operation_id self.response_model_include = response_model_include self.response_model_exclude = response_model_exclude self.response_model_by_alias = response_model_by_alias self.response_model_skip_defaults = response_model_skip_defaults self.include_in_schema = include_in_schema self.response_class = response_class self.path_regex, self.path_format, self.param_convertors = compile_path(path) assert inspect.isfunction(endpoint) or inspect.ismethod(endpoint), ( f"An endpoint must be a function or method" ) self.dependant = get_dependant(path=self.path_format, call=self.endpoint) for depends in self.dependencies[::-1]: self.dependant.dependencies.insert( 0, get_parameterless_sub_dependant(depends=depends, path=self.path_format), ) self.body_field = get_body_field(dependant=self.dependant, name=self.name) self.dependency_overrides_provider = dependency_overrides_provider self.app = request_response( get_app( dependant=self.dependant, body_field=self.body_field, status_code=self.status_code, response_class=self.response_class, response_field=self.secure_cloned_response_field, response_model_include=self.response_model_include, response_model_exclude=self.response_model_exclude, response_model_by_alias=self.response_model_by_alias, response_model_skip_defaults=self.response_model_skip_defaults, dependency_overrides_provider=self.dependency_overrides_provider, ) )
https://github.com/tiangolo/fastapi/issues/284
ip-10-8-0-198% % uvicorn run:app --reload INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit) INFO: Started reloader process [77186] WARNING:root:email-validator not installed, email fields will be treated as str. To install, run: pip install email-validator INFO:uvicorn:Started server process [77188] INFO:uvicorn:Waiting for application startup. INFO:uvicorn:('127.0.0.1', 54932) - "GET /docs HTTP/1.1" 200 INFO:uvicorn:('127.0.0.1', 54932) - "GET /openapi.json HTTP/1.1" 500 ERROR:uvicorn:Exception in ASGI application Traceback (most recent call last): File "/Users/edwardbanner/.anaconda/lib/python3.6/site-packages/uvicorn/protocols/http/httptools_impl.py", line 368, in run_asgi result = await app(self.scope, self.receive, self.send) File "/Users/edwardbanner/.anaconda/lib/python3.6/site-packages/uvicorn/middleware/asgi2.py", line 7, in __call__ await instance(receive, send) File "/Users/edwardbanner/.anaconda/lib/python3.6/site-packages/starlette/middleware/errors.py", line 125, in asgi raise exc from None File "/Users/edwardbanner/.anaconda/lib/python3.6/site-packages/starlette/middleware/errors.py", line 103, in asgi await asgi(receive, _send) File "/Users/edwardbanner/.anaconda/lib/python3.6/site-packages/starlette/exceptions.py", line 74, in app raise exc from None File "/Users/edwardbanner/.anaconda/lib/python3.6/site-packages/starlette/exceptions.py", line 63, in app await instance(receive, sender) File "/Users/edwardbanner/.anaconda/lib/python3.6/site-packages/starlette/routing.py", line 43, in awaitable response = await run_in_threadpool(func, request) File "/Users/edwardbanner/.anaconda/lib/python3.6/site-packages/starlette/concurrency.py", line 24, in run_in_threadpool return await loop.run_in_executor(None, func, *args) File "/Users/edwardbanner/.anaconda/lib/python3.6/concurrent/futures/thread.py", line 56, in run result = self.fn(*self.args, **self.kwargs) File "/Users/edwardbanner/.anaconda/lib/python3.6/site-packages/fastapi/applications.py", line 83, in <lambda> lambda req: JSONResponse(self.openapi()), File "/Users/edwardbanner/.anaconda/lib/python3.6/site-packages/fastapi/applications.py", line 75, in openapi openapi_prefix=self.openapi_prefix, File "/Users/edwardbanner/.anaconda/lib/python3.6/site-packages/fastapi/openapi/utils.py", line 248, in get_openapi flat_models=flat_models, model_name_map=model_name_map File "/Users/edwardbanner/.anaconda/lib/python3.6/site-packages/fastapi/utils.py", line 45, in get_model_definitions model_name = model_name_map[model] KeyError: <class 'Body_compute'>
KeyError
def get_flat_models_from_routes( routes: Sequence[Type[BaseRoute]], ) -> Set[Type[BaseModel]]: body_fields_from_routes: List[Field] = [] responses_from_routes: List[Field] = [] for route in routes: if getattr(route, "include_in_schema", None) and isinstance( route, routing.APIRoute ): if route.body_field: assert isinstance(route.body_field, Field), ( "A request body must be a Pydantic Field" ) body_fields_from_routes.append(route.body_field) if route.response_field: responses_from_routes.append(route.response_field) if route.response_fields: responses_from_routes.extend(route.response_fields.values()) flat_models = get_flat_models_from_fields( body_fields_from_routes + responses_from_routes, known_models=set() ) return flat_models
def get_flat_models_from_routes( routes: Sequence[Type[BaseRoute]], ) -> Set[Type[BaseModel]]: body_fields_from_routes: List[Field] = [] responses_from_routes: List[Field] = [] for route in routes: if getattr(route, "include_in_schema", None) and isinstance( route, routing.APIRoute ): if route.body_field: assert isinstance(route.body_field, Field), ( "A request body must be a Pydantic Field" ) body_fields_from_routes.append(route.body_field) if route.response_field: responses_from_routes.append(route.response_field) if route.response_fields: responses_from_routes.extend(route.response_fields.values()) flat_models = get_flat_models_from_fields( body_fields_from_routes + responses_from_routes ) return flat_models
https://github.com/tiangolo/fastapi/issues/308
INFO: ('127.0.0.1', 55246) - "GET /openapi.json HTTP/1.1" 500 ERROR: Exception in ASGI application Traceback (most recent call last): File "c:\users\user\.virtualenvs\server-xl-s7lqx\lib\site-packages\uvicorn\protocols\http\h11_impl.py", line 369, in run_asgi result = await app(self.scope, self.receive, self.send) File "c:\users\user\.virtualenvs\server-xl-s7lqx\lib\site-packages\starlette\applications.py", line 133, in __call__ await self.error_middleware(scope, receive, send) File "c:\users\user\.virtualenvs\server-xl-s7lqx\lib\site-packages\starlette\middleware\errors.py", line 122, in __call__ raise exc from None File "c:\users\user\.virtualenvs\server-xl-s7lqx\lib\site-packages\starlette\middleware\errors.py", line 100, in __call__ await self.app(scope, receive, _send) File "c:\users\user\.virtualenvs\server-xl-s7lqx\lib\site-packages\starlette\exceptions.py", line 73, in __call__ raise exc from None File "c:\users\user\.virtualenvs\server-xl-s7lqx\lib\site-packages\starlette\exceptions.py", line 62, in __call__ await self.app(scope, receive, sender) File "c:\users\user\.virtualenvs\server-xl-s7lqx\lib\site-packages\starlette\routing.py", line 585, in __call__ await route(scope, receive, send) File "c:\users\user\.virtualenvs\server-xl-s7lqx\lib\site-packages\starlette\routing.py", line 207, in __call__ await self.app(scope, receive, send) File "c:\users\user\.virtualenvs\server-xl-s7lqx\lib\site-packages\starlette\routing.py", line 40, in app response = await func(request) File "c:\users\user\.virtualenvs\server-xl-s7lqx\lib\site-packages\fastapi\applications.py", line 87, in openapi return JSONResponse(self.openapi()) File "c:\users\user\.virtualenvs\server-xl-s7lqx\lib\site-packages\fastapi\applications.py", line 79, in openapi openapi_prefix=self.openapi_prefix, File "c:\users\user\.virtualenvs\server-xl-s7lqx\lib\site-packages\fastapi\openapi\utils.py", line 241, in get_openapi flat_models = get_flat_models_from_routes(routes) File "c:\users\user\.virtualenvs\server-xl-s7lqx\lib\site-packages\fastapi\utils.py", line 31, in get_flat_models_from_routes body_fields_from_routes + responses_from_routes TypeError: get_flat_models_from_fields() missing 1 required positional argument: 'known_models'
TypeError
def __init__(self, master): _Base.__init__(self, master) self.name = "Controller" self.variables = [ ("grbl_0", "float", 10, _("$0 Step pulse time [us]")), ("grbl_1", "int", 25, _("$1 Step idle delay [ms]")), ("grbl_2", "int", 0, _("$2 Step port invert [mask]")), ("grbl_3", "int", 0, _("$3 Direction port invert [mask]")), ("grbl_4", "bool", 0, _("$4 Step enable invert")), ("grbl_5", "bool", 0, _("$5 Limit pins invert")), ("grbl_6", "bool", 0, _("$6 Probe pin invert")), ("grbl_10", "int", 1, _("$10 Status report [mask]")), ("grbl_11", "float", 0.010, _("$11 Junction deviation [mm]")), ("grbl_12", "float", 0.002, _("$12 Arc tolerance [mm]")), ("grbl_13", "bool", 0, _("$13 Report inches")), ("grbl_20", "bool", 0, _("$20 Soft limits")), ("grbl_21", "bool", 0, _("$21 Hard limits")), ("grbl_22", "bool", 0, _("$22 Homing cycle")), ("grbl_23", "int", 0, _("$23 Homing direction invert [mask]")), ("grbl_24", "float", 25.0, _("$24 Homing feed [mm/min]")), ("grbl_25", "float", 500.0, _("$25 Homing seek [mm/min]")), ("grbl_26", "int", 250, _("$26 Homing debounce [ms]")), ("grbl_27", "float", 1.0, _("$27 Homing pull-off [mm]")), ("grbl_30", "float", 1000.0, _("$30 Max spindle speed [RPM]")), ("grbl_31", "float", 0.0, _("$31 Min spindle speed [RPM]")), ("grbl_32", "bool", 0, _("$32 Laser mode enable")), ("grbl_100", "float", 250.0, _("$100 X steps/mm")), ("grbl_101", "float", 250.0, _("$101 Y steps/mm")), ("grbl_102", "float", 250.0, _("$102 Z steps/mm")), ("grbl_110", "float", 500.0, _("$110 X max rate [mm/min]")), ("grbl_111", "float", 500.0, _("$111 Y max rate [mm/min]")), ("grbl_112", "float", 500.0, _("$112 Z max rate [mm/min]")), ("grbl_120", "float", 10.0, _("$120 X acceleration [mm/sec^2]")), ("grbl_121", "float", 10.0, _("$121 Y acceleration [mm/sec^2]")), ("grbl_122", "float", 10.0, _("$122 Z acceleration [mm/sec^2]")), ("grbl_130", "float", 200.0, _("$130 X max travel [mm]")), ("grbl_131", "float", 200.0, _("$131 Y max travel [mm]")), ("grbl_132", "float", 200.0, _("$132 Z max travel [mm]")), ("grbl_140", "float", 200.0, _("$140 X homing pull-off [mm]")), ("grbl_141", "float", 200.0, _("$141 Y homing pull-off [mm]")), ("grbl_142", "float", 200.0, _("$142 Z homing pull-off [mm]")), ] self.buttons.append("exe")
def __init__(self, master): _Base.__init__(self, master) self.name = "Controller" self.variables = [ ("grbl_0", "int", 10, _("$0 Step pulse time [us]")), ("grbl_1", "int", 25, _("$1 Step idle delay [ms]")), ("grbl_2", "int", 0, _("$2 Step port invert [mask]")), ("grbl_3", "int", 0, _("$3 Direction port invert [mask]")), ("grbl_4", "bool", 0, _("$4 Step enable invert")), ("grbl_5", "bool", 0, _("$5 Limit pins invert")), ("grbl_6", "bool", 0, _("$6 Probe pin invert")), ("grbl_10", "int", 1, _("$10 Status report [mask]")), ("grbl_11", "float", 0.010, _("$11 Junction deviation [mm]")), ("grbl_12", "float", 0.002, _("$12 Arc tolerance [mm]")), ("grbl_13", "bool", 0, _("$13 Report inches")), ("grbl_20", "bool", 0, _("$20 Soft limits")), ("grbl_21", "bool", 0, _("$21 Hard limits")), ("grbl_22", "bool", 0, _("$22 Homing cycle")), ("grbl_23", "int", 0, _("$23 Homing direction invert [mask]")), ("grbl_24", "float", 25.0, _("$24 Homing feed [mm/min]")), ("grbl_25", "float", 500.0, _("$25 Homing seek [mm/min]")), ("grbl_26", "int", 250, _("$26 Homing debounce [ms]")), ("grbl_27", "float", 1.0, _("$27 Homing pull-off [mm]")), ("grbl_30", "float", 1000.0, _("$30 Max spindle speed [RPM]")), ("grbl_31", "float", 0.0, _("$31 Min spindle speed [RPM]")), ("grbl_32", "bool", 0, _("$32 Laser mode enable")), ("grbl_100", "float", 250.0, _("$100 X steps/mm")), ("grbl_101", "float", 250.0, _("$101 Y steps/mm")), ("grbl_102", "float", 250.0, _("$102 Z steps/mm")), ("grbl_110", "float", 500.0, _("$110 X max rate [mm/min]")), ("grbl_111", "float", 500.0, _("$111 Y max rate [mm/min]")), ("grbl_112", "float", 500.0, _("$112 Z max rate [mm/min]")), ("grbl_120", "float", 10.0, _("$120 X acceleration [mm/sec^2]")), ("grbl_121", "float", 10.0, _("$121 Y acceleration [mm/sec^2]")), ("grbl_122", "float", 10.0, _("$122 Z acceleration [mm/sec^2]")), ("grbl_130", "float", 200.0, _("$130 X max travel [mm]")), ("grbl_131", "float", 200.0, _("$131 Y max travel [mm]")), ("grbl_132", "float", 200.0, _("$132 Z max travel [mm]")), ("grbl_140", "float", 200.0, _("$140 X homing pull-off [mm]")), ("grbl_141", "float", 200.0, _("$141 Y homing pull-off [mm]")), ("grbl_142", "float", 200.0, _("$142 Z homing pull-off [mm]")), ] self.buttons.append("exe")
https://github.com/vlachoudis/bCNC/issues/1463
Program : bCNC Version : 0.9.14-dev Last Change : 8 Jan 2019 Platform : linux2 Python : 2.7.17 (default, Nov 7 2019, 10:07:09) [GCC 9.2.1 20191008] TkVersion : 8.6 TclVersion : 8.6 Traceback: Traceback (most recent call last): File "/home/randolph/.local/lib/python2.7/site-packages/bCNC/Utils.py", line 464, in __call__ return self.func(*args) File "/home/randolph/.local/lib/python2.7/site-packages/bCNC/bCNC.py", line 2011, in loadDialog if filename: self.load(filename) File "/home/randolph/.local/lib/python2.7/site-packages/bCNC/bCNC.py", line 2089, in load Page.frames["CAM"].populate() File "/home/randolph/.local/lib/python2.7/site-packages/bCNC/ToolsPage.py", line 1709, in change tool.populate() File "/home/randolph/.local/lib/python2.7/site-packages/bCNC/ToolsPage.py", line 1065, in populate self.values[n] = int(CNC.vars[n]) ValueError: invalid literal for int() with base 10: '250.000' Traceback (most recent call last): File "/home/randolph/.local/lib/python2.7/site-packages/bCNC/Utils.py", line 464, in __call__ return self.func(*args) File "/home/randolph/.local/lib/python2.7/site-packages/bCNC/bCNC.py", line 2011, in loadDialog if filename: self.load(filename) File "/home/randolph/.local/lib/python2.7/site-packages/bCNC/bCNC.py", line 2089, in load Page.frames["CAM"].populate() File "/home/randolph/.local/lib/python2.7/site-packages/bCNC/ToolsPage.py", line 1709, in change tool.populate() File "/home/randolph/.local/lib/python2.7/site-packages/bCNC/ToolsPage.py", line 1065, in populate self.values[n] = int(CNC.vars[n]) ValueError: invalid literal for int() with base 10: '250.000' Traceback (most recent call last): File "/home/randolph/.local/lib/python2.7/site-packages/bCNC/Utils.py", line 464, in __call__ return self.func(*args) File "/home/randolph/.local/lib/python2.7/site-packages/bCNC/bCNC.py", line 2011, in loadDialog if filename: self.load(filename) File "/home/randolph/.local/lib/python2.7/site-packages/bCNC/bCNC.py", line 2089, in load Page.frames["CAM"].populate() File "/home/randolph/.local/lib/python2.7/site-packages/bCNC/ToolsPage.py", line 1709, in change tool.populate() File "/home/randolph/.local/lib/python2.7/site-packages/bCNC/ToolsPage.py", line 1065, in populate self.values[n] = int(CNC.vars[n]) ValueError: invalid literal for int() with base 10: '250.000'
ValueError
def copy(self): """Return a shallow copy of the instance.""" rv = self.__class__(self.capacity) rv._mapping.update(self._mapping) rv._queue.extend(self._queue) return rv
def copy(self): """Return a shallow copy of the instance.""" rv = self.__class__(self.capacity) rv._mapping.update(self._mapping) rv._queue = deque(self._queue) return rv
https://github.com/pallets/jinja/issues/843
from jinja2 import utils cache = utils.LRUCache(1) cache['foo'] = 'bar' copy = cache.copy() copy['blah'] = 'blargh' Traceback (most recent call last): File "<stdin>", line 1, in <module> File "jinja2/utils.py", line 424, in __setitem__ del self._mapping[self._popleft()] IndexError: pop from an empty deque copy._popleft <built-in method popleft of collections.deque object at 0x10160d670> copy._queue.popleft <built-in method popleft of collections.deque object at 0x101635360>
IndexError
def open_if_exists(filename, mode="rb"): """Returns a file descriptor for the filename if that file exists, otherwise ``None``. """ if not os.path.isfile(filename): return None return open(filename, mode)
def open_if_exists(filename, mode="rb"): """Returns a file descriptor for the filename if that file exists, otherwise `None`. """ try: return open(filename, mode) except IOError as e: if e.errno not in (errno.ENOENT, errno.EISDIR, errno.EINVAL): raise
https://github.com/pallets/jinja/issues/821
IOError: [Errno 20] Not a directory: 'dir1/foo/test' from jinja2 import FileSystemLoader, Environment loader = FileSystemLoader(['dir1', 'dir2']) env = Environment(loader=loader) env.get_template('foo/test') Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/usr/lib/python2.7/site-packages/jinja2/environment.py", line 830, in get_template return self._load_template(name, self.make_globals(globals)) File "/usr/lib/python2.7/site-packages/jinja2/environment.py", line 804, in _load_template template = self.loader.load(self, name, globals) File "/usr/lib/python2.7/site-packages/jinja2/loaders.py", line 113, in load source, filename, uptodate = self.get_source(environment, name) File "/usr/lib/python2.7/site-packages/jinja2/loaders.py", line 171, in get_source f = open_if_exists(filename) File "/usr/lib/python2.7/site-packages/jinja2/utils.py", line 154, in open_if_exists return open(filename, mode) IOError: [Errno 20] Not a directory: 'dir1/foo/test'
IOError
def __init__(self, environment, parent, name, blocks): self.parent = parent self.vars = {} self.environment = environment self.eval_ctx = EvalContext(self.environment, name) self.exported_vars = set() self.name = name # create the initial mapping of blocks. Whenever template inheritance # takes place the runtime will update this mapping with the new blocks # from the template. self.blocks = dict((k, [v]) for k, v in iteritems(blocks)) # In case we detect the fast resolve mode we can set up an alias # here that bypasses the legacy code logic. if self._fast_resolve_mode: self.resolve_or_missing = MethodType(resolve_or_missing, self)
def __init__(self, environment, parent, name, blocks): self.parent = parent self.vars = {} self.environment = environment self.eval_ctx = EvalContext(self.environment, name) self.exported_vars = set() self.name = name # create the initial mapping of blocks. Whenever template inheritance # takes place the runtime will update this mapping with the new blocks # from the template. self.blocks = dict((k, [v]) for k, v in iteritems(blocks)) # In case we detect the fast resolve mode we can set up an alias # here that bypasses the legacy code logic. if self._fast_resolve_mode: self.resolve_or_missing = resolve_or_missing
https://github.com/pallets/jinja/issues/675
Traceback (most recent call last): File "test.py", line 16, in <module> print env.get_template('test').render(foobar='test') File "/home/adrian/dev/indico/env/lib/python2.7/site-packages/jinja2/environment.py", line 1008, in render return self.environment.handle_exception(exc_info, True) File "/home/adrian/dev/indico/env/lib/python2.7/site-packages/jinja2/environment.py", line 780, in handle_exception reraise(exc_type, exc_value, tb) File "<template>", line 1, in top-level template code File "<template>", line 1, in top-level template code TypeError: resolve_or_missing() takes at least 2 arguments (1 given)
TypeError
def visit_Template(self, node, frame=None): assert frame is None, "no root frame allowed" eval_ctx = EvalContext(self.environment, self.name) from jinja2.runtime import __all__ as exported self.writeline("from __future__ import %s" % ", ".join(code_features)) self.writeline("from jinja2.runtime import " + ", ".join(exported)) if self.environment.is_async: self.writeline( "from jinja2.asyncsupport import auto_await, " "auto_aiter, make_async_loop_context" ) # if we want a deferred initialization we cannot move the # environment into a local name envenv = not self.defer_init and ", environment=environment" or "" # do we have an extends tag at all? If not, we can save some # overhead by just not processing any inheritance code. have_extends = node.find(nodes.Extends) is not None # find all blocks for block in node.find_all(nodes.Block): if block.name in self.blocks: self.fail("block %r defined twice" % block.name, block.lineno) self.blocks[block.name] = block # find all imports and import them for import_ in node.find_all(nodes.ImportedName): if import_.importname not in self.import_aliases: imp = import_.importname self.import_aliases[imp] = alias = self.temporary_identifier() if "." in imp: module, obj = imp.rsplit(".", 1) self.writeline("from %s import %s as %s" % (module, obj, alias)) else: self.writeline("import %s as %s" % (imp, alias)) # add the load name self.writeline("name = %r" % self.name) # generate the root render function. self.writeline( "%s(context, missing=missing%s):" % (self.func("root"), envenv), extra=1 ) self.indent() self.write_commons() # process the root frame = Frame(eval_ctx) if "self" in find_undeclared(node.body, ("self",)): ref = frame.symbols.declare_parameter("self") self.writeline("%s = TemplateReference(context)" % ref) frame.symbols.analyze_node(node) frame.toplevel = frame.rootlevel = True frame.require_output_check = have_extends and not self.has_known_extends if have_extends: self.writeline("parent_template = None") self.enter_frame(frame) self.pull_dependencies(node.body) self.blockvisit(node.body, frame) self.leave_frame(frame, with_python_scope=True) self.outdent() # make sure that the parent root is called. if have_extends: if not self.has_known_extends: self.indent() self.writeline("if parent_template is not None:") self.indent() if supports_yield_from and not self.environment.is_async: self.writeline("yield from parent_template.root_render_func(context)") else: self.writeline( "%sfor event in parent_template." "root_render_func(context):" % (self.environment.is_async and "async " or "") ) self.indent() self.writeline("yield event") self.outdent() self.outdent(1 + (not self.has_known_extends)) # at this point we now have the blocks collected and can visit them too. for name, block in iteritems(self.blocks): self.writeline( "%s(context, missing=missing%s):" % (self.func("block_" + name), envenv), block, 1, ) self.indent() self.write_commons() # It's important that we do not make this frame a child of the # toplevel template. This would cause a variety of # interesting issues with identifier tracking. block_frame = Frame(eval_ctx) undeclared = find_undeclared(block.body, ("self", "super")) if "self" in undeclared: ref = block_frame.symbols.declare_parameter("self") self.writeline("%s = TemplateReference(context)" % ref) if "super" in undeclared: ref = block_frame.symbols.declare_parameter("super") self.writeline("%s = context.super(%r, block_%s)" % (ref, name, name)) block_frame.symbols.analyze_node(block) block_frame.block = name self.enter_frame(block_frame) self.pull_dependencies(block.body) self.blockvisit(block.body, block_frame) self.leave_frame(block_frame, with_python_scope=True) self.outdent() self.writeline( "blocks = {%s}" % ", ".join("%r: block_%s" % (x, x) for x in self.blocks), extra=1, ) # add a function that returns the debug info self.writeline("debug_info = %r" % "&".join("%s=%s" % x for x in self.debug_info))
def visit_Template(self, node, frame=None): assert frame is None, "no root frame allowed" eval_ctx = EvalContext(self.environment, self.name) from jinja2.runtime import __all__ as exported self.writeline("from __future__ import %s" % ", ".join(code_features)) self.writeline("from jinja2.runtime import " + ", ".join(exported)) if self.environment.is_async: self.writeline( "from jinja2.asyncsupport import auto_await, " "auto_aiter, make_async_loop_context" ) # if we want a deferred initialization we cannot move the # environment into a local name envenv = not self.defer_init and ", environment=environment" or "" # do we have an extends tag at all? If not, we can save some # overhead by just not processing any inheritance code. have_extends = node.find(nodes.Extends) is not None # find all blocks for block in node.find_all(nodes.Block): if block.name in self.blocks: self.fail("block %r defined twice" % block.name, block.lineno) self.blocks[block.name] = block # find all imports and import them for import_ in node.find_all(nodes.ImportedName): if import_.importname not in self.import_aliases: imp = import_.importname self.import_aliases[imp] = alias = self.temporary_identifier() if "." in imp: module, obj = imp.rsplit(".", 1) self.writeline("from %s import %s as %s" % (module, obj, alias)) else: self.writeline("import %s as %s" % (imp, alias)) # add the load name self.writeline("name = %r" % self.name) # generate the root render function. self.writeline( "%s(context, missing=missing%s):" % (self.func("root"), envenv), extra=1 ) self.indent() self.write_commons() # process the root frame = Frame(eval_ctx) if "self" in find_undeclared(node.body, ("self",)): ref = frame.symbols.declare_parameter("self") self.writeline("%s = TemplateReference(context)" % ref) frame.symbols.analyze_node(node) frame.toplevel = frame.rootlevel = True frame.require_output_check = have_extends and not self.has_known_extends if have_extends: self.writeline("parent_template = None") self.enter_frame(frame) self.pull_dependencies(node.body) self.blockvisit(node.body, frame) self.leave_frame(frame, with_python_scope=True) self.outdent() # make sure that the parent root is called. if have_extends: if not self.has_known_extends: self.indent() self.writeline("if parent_template is not None:") self.indent() if supports_yield_from: self.writeline("yield from parent_template.root_render_func(context)") else: self.writeline("for event in parent_template.root_render_func(context):") self.indent() self.writeline("yield event") self.outdent() self.outdent(1 + (not self.has_known_extends)) # at this point we now have the blocks collected and can visit them too. for name, block in iteritems(self.blocks): self.writeline( "%s(context, missing=missing%s):" % (self.func("block_" + name), envenv), block, 1, ) self.indent() self.write_commons() # It's important that we do not make this frame a child of the # toplevel template. This would cause a variety of # interesting issues with identifier tracking. block_frame = Frame(eval_ctx) undeclared = find_undeclared(block.body, ("self", "super")) if "self" in undeclared: ref = block_frame.symbols.declare_parameter("self") self.writeline("%s = TemplateReference(context)" % ref) if "super" in undeclared: ref = block_frame.symbols.declare_parameter("super") self.writeline("%s = context.super(%r, block_%s)" % (ref, name, name)) block_frame.symbols.analyze_node(block) block_frame.block = name self.enter_frame(block_frame) self.pull_dependencies(block.body) self.blockvisit(block.body, block_frame) self.leave_frame(block_frame, with_python_scope=True) self.outdent() self.writeline( "blocks = {%s}" % ", ".join("%r: block_%s" % (x, x) for x in self.blocks), extra=1, ) # add a function that returns the debug info self.writeline("debug_info = %r" % "&".join("%s=%s" % x for x in self.debug_info))
https://github.com/pallets/jinja/issues/668
Exception occurred while handling uri: "/1" Traceback (most recent call last): File "/Users/mohamed/.virtualenvs/item.tf/lib/python3.6/site-packages/sanic/sanic.py", line 208, in handle_request response = await response File "/opt/local/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/asyncio/coroutines.py", line 109, in __next__ return self.gen.send(None) File "main.py", line 88, in item description=' | '.join(desc_list)) File "/opt/local/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/asyncio/coroutines.py", line 109, in __next__ return self.gen.send(None) File "main.py", line 307, in render template = jinja_env.get_template(template) File "/Users/mohamed/.virtualenvs/item.tf/lib/python3.6/site-packages/jinja2/environment.py", line 833, in get_template return self._load_template(name, self.make_globals(globals)) File "/Users/mohamed/.virtualenvs/item.tf/lib/python3.6/site-packages/jinja2/environment.py", line 807, in _load_template template = self.loader.load(self, name, globals) File "/Users/mohamed/.virtualenvs/item.tf/lib/python3.6/site-packages/jinja2/loaders.py", line 125, in load code = environment.compile(source, name, filename) File "/Users/mohamed/.virtualenvs/item.tf/lib/python3.6/site-packages/jinja2/environment.py", line 590, in compile return self._compile(source, filename) File "/Users/mohamed/.virtualenvs/item.tf/lib/python3.6/site-packages/jinja2/environment.py", line 552, in _compile return compile(source, filename, 'exec') File "templates/item.html", line 15 ^ SyntaxError: 'yield from' inside async function
SyntaxError
def visit_For(self, node, frame): loop_frame = frame.inner() test_frame = frame.inner() else_frame = frame.inner() # try to figure out if we have an extended loop. An extended loop # is necessary if the loop is in recursive mode if the special loop # variable is accessed in the body. extended_loop = node.recursive or "loop" in find_undeclared( node.iter_child_nodes(only=("body",)), ("loop",) ) loop_ref = None if extended_loop: loop_ref = loop_frame.symbols.declare_parameter("loop") loop_frame.symbols.analyze_node(node, for_branch="body") if node.else_: else_frame.symbols.analyze_node(node, for_branch="else") if node.test: loop_filter_func = self.temporary_identifier() test_frame.symbols.analyze_node(node, for_branch="test") self.writeline("%s(fiter):" % self.func(loop_filter_func), node.test) self.indent() self.enter_frame(test_frame) self.writeline(self.environment.is_async and "async for " or "for ") self.visit(node.target, loop_frame) self.write(" in ") self.write(self.environment.is_async and "auto_aiter(fiter)" or "fiter") self.write(":") self.indent() self.writeline("if ", node.test) self.visit(node.test, test_frame) self.write(":") self.indent() self.writeline("yield ") self.visit(node.target, loop_frame) self.outdent(3) self.leave_frame(test_frame, with_python_scope=True) # if we don't have an recursive loop we have to find the shadowed # variables at that point. Because loops can be nested but the loop # variable is a special one we have to enforce aliasing for it. if node.recursive: self.writeline( "%s(reciter, loop_render_func, depth=0):" % self.func("loop"), node ) self.indent() self.buffer(loop_frame) # Use the same buffer for the else frame else_frame.buffer = loop_frame.buffer # make sure the loop variable is a special one and raise a template # assertion error if a loop tries to write to loop if extended_loop: self.writeline("%s = missing" % loop_ref) for name in node.find_all(nodes.Name): if name.ctx == "store" and name.name == "loop": self.fail( "Can't assign to special loop variable in for-loop target", name.lineno ) if node.else_: iteration_indicator = self.temporary_identifier() self.writeline("%s = 1" % iteration_indicator) self.writeline(self.environment.is_async and "async for " or "for ", node) self.visit(node.target, loop_frame) if extended_loop: if self.environment.is_async: self.write(", %s in await make_async_loop_context(" % loop_ref) else: self.write(", %s in LoopContext(" % loop_ref) else: self.write(" in ") if node.test: self.write("%s(" % loop_filter_func) if node.recursive: self.write("reciter") else: if self.environment.is_async and not extended_loop: self.write("auto_aiter(") self.visit(node.iter, frame) if self.environment.is_async and not extended_loop: self.write(")") if node.test: self.write(")") if node.recursive: self.write(", loop_render_func, depth):") else: self.write(extended_loop and "):" or ":") self.indent() self.enter_frame(loop_frame) self.blockvisit(node.body, loop_frame) if node.else_: self.writeline("%s = 0" % iteration_indicator) self.outdent() self.leave_frame(loop_frame, with_python_scope=node.recursive and not node.else_) if node.else_: self.writeline("if %s:" % iteration_indicator) self.indent() self.enter_frame(else_frame) self.blockvisit(node.else_, else_frame) self.leave_frame(else_frame) self.outdent() # if the node was recursive we have to return the buffer contents # and start the iteration code if node.recursive: self.return_buffer_contents(loop_frame) self.outdent() self.start_write(frame, node) if self.environment.is_async: self.write("await ") self.write("loop(") if self.environment.is_async: self.write("auto_aiter(") self.visit(node.iter, frame) if self.environment.is_async: self.write(")") self.write(", loop)") self.end_write(frame)
def visit_For(self, node, frame): loop_frame = frame.inner() test_frame = frame.inner() else_frame = frame.inner() # try to figure out if we have an extended loop. An extended loop # is necessary if the loop is in recursive mode if the special loop # variable is accessed in the body. extended_loop = node.recursive or "loop" in find_undeclared( node.iter_child_nodes(only=("body",)), ("loop",) ) loop_ref = None if extended_loop: loop_ref = loop_frame.symbols.declare_parameter("loop") loop_frame.symbols.analyze_node(node, for_branch="body") if node.else_: else_frame.symbols.analyze_node(node, for_branch="else") if node.test: loop_filter_func = self.temporary_identifier() test_frame.symbols.analyze_node(node, for_branch="test") self.writeline("%s(fiter):" % self.func(loop_filter_func), node.test) self.indent() self.enter_frame(test_frame) self.writeline(self.environment.is_async and "async for " or "for ") self.visit(node.target, loop_frame) self.write(" in ") self.write(self.environment.is_async and "auto_aiter(fiter)" or "fiter") self.write(":") self.indent() self.writeline("if ", node.test) self.visit(node.test, test_frame) self.write(":") self.indent() self.writeline("yield ") self.visit(node.target, loop_frame) self.outdent(3) self.leave_frame(test_frame, with_python_scope=True) # if we don't have an recursive loop we have to find the shadowed # variables at that point. Because loops can be nested but the loop # variable is a special one we have to enforce aliasing for it. if node.recursive: self.writeline( "%s(reciter, loop_render_func, depth=0):" % self.func("loop"), node ) self.indent() self.buffer(loop_frame) # make sure the loop variable is a special one and raise a template # assertion error if a loop tries to write to loop if extended_loop: self.writeline("%s = missing" % loop_ref) for name in node.find_all(nodes.Name): if name.ctx == "store" and name.name == "loop": self.fail( "Can't assign to special loop variable in for-loop target", name.lineno ) if node.else_: iteration_indicator = self.temporary_identifier() self.writeline("%s = 1" % iteration_indicator) self.writeline(self.environment.is_async and "async for " or "for ", node) self.visit(node.target, loop_frame) if extended_loop: if self.environment.is_async: self.write(", %s in await make_async_loop_context(" % loop_ref) else: self.write(", %s in LoopContext(" % loop_ref) else: self.write(" in ") if node.test: self.write("%s(" % loop_filter_func) if node.recursive: self.write("reciter") else: if self.environment.is_async and not extended_loop: self.write("auto_aiter(") self.visit(node.iter, frame) if self.environment.is_async and not extended_loop: self.write(")") if node.test: self.write(")") if node.recursive: self.write(", loop_render_func, depth):") else: self.write(extended_loop and "):" or ":") self.indent() self.enter_frame(loop_frame) self.blockvisit(node.body, loop_frame) if node.else_: self.writeline("%s = 0" % iteration_indicator) self.outdent() self.leave_frame(loop_frame, with_python_scope=node.recursive and not node.else_) if node.else_: self.writeline("if %s:" % iteration_indicator) self.indent() self.enter_frame(else_frame) self.blockvisit(node.else_, else_frame) self.leave_frame(else_frame) self.outdent() # if the node was recursive we have to return the buffer contents # and start the iteration code if node.recursive: self.return_buffer_contents(loop_frame) self.outdent() self.start_write(frame, node) if self.environment.is_async: self.write("await ") self.write("loop(") if self.environment.is_async: self.write("auto_aiter(") self.visit(node.iter, frame) if self.environment.is_async: self.write(")") self.write(", loop)") self.end_write(frame)
https://github.com/pallets/jinja/issues/669
import jinja2 jinja2.Template('{% for value in values recursive %}1{% else %}0{% endfor %}').render(values=[]) Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/home/ustr/environ/local/lib/python2.7/site-packages/jinja2/environment.py", line 945, in __new__ return env.from_string(source, template_class=cls) File "/home/ustr/environ/local/lib/python2.7/site-packages/jinja2/environment.py", line 880, in from_string return cls.from_code(self, self.compile(source), globals, None) File "/home/ustr/environ/local/lib/python2.7/site-packages/jinja2/environment.py", line 588, in compile return self._compile(source, filename) File "/home/ustr/environ/local/lib/python2.7/site-packages/jinja2/environment.py", line 551, in _compile return compile(source, filename, 'exec') File "<template>", line 25 SyntaxError: 'return' with argument inside generator
SyntaxError
def _convert_flattened_paths( paths: List, quantization: float, scale_x: float, scale_y: float, offset_x: float, offset_y: float, simplify: bool, ) -> "LineCollection": """Convert a list of FlattenedPaths to a :class:`LineCollection`. Args: paths: list of FlattenedPaths quantization: maximum length of linear elements to approximate curve paths scale_x, scale_y: scale factor to apply offset_x, offset_y: offset to apply simplify: should Shapely's simplify be run Returns: new :class:`LineCollection` instance containing the converted geometries """ lc = LineCollection() for result in paths: # Here we load the sub-part of the path element. If such sub-parts are connected, # we merge them in a single line (e.g. line string, etc.). If there are disconnection # in the path (e.g. multiple "M" commands), we create several lines sub_paths: List[List[complex]] = [] for elem in result: if isinstance(elem, svg.Line): coords = [elem.start, elem.end] else: # This is a curved element that we approximate with small segments step = int(math.ceil(elem.length() / quantization)) coords = [elem.start] coords.extend(elem.point((i + 1) / step) for i in range(step - 1)) coords.append(elem.end) # merge to last sub path if first coordinates match if sub_paths: if sub_paths[-1][-1] == coords[0]: sub_paths[-1].extend(coords[1:]) else: sub_paths.append(coords) else: sub_paths.append(coords) for sub_path in sub_paths: path = np.array(sub_path) # transform path += offset_x + 1j * offset_y path.real *= scale_x path.imag *= scale_y lc.append(path) if simplify: mls = lc.as_mls() lc = LineCollection(mls.simplify(tolerance=quantization)) return lc
def _convert_flattened_paths( paths: List, quantization: float, scale_x: float, scale_y: float, offset_x: float, offset_y: float, simplify: bool, ) -> "LineCollection": """Convert a list of FlattenedPaths to a :class:`LineCollection`. Args: paths: list of FlattenedPaths quantization: maximum length of linear elements to approximate curve paths scale_x, scale_y: scale factor to apply offset_x, offset_y: offset to apply simplify: should Shapely's simplify be run Returns: new :class:`LineCollection` instance containing the converted geometries """ lc = LineCollection() for result in paths: # Here we load the sub-part of the path element. If such sub-parts are connected, # we merge them in a single line (e.g. line string, etc.). If there are disconnection # in the path (e.g. multiple "M" commands), we create several lines sub_paths: List[List[complex]] = [] for elem in result.path: if isinstance(elem, svg.Line): coords = [elem.start, elem.end] else: # This is a curved element that we approximate with small segments step = int(math.ceil(elem.length() / quantization)) coords = [elem.start] coords.extend(elem.point((i + 1) / step) for i in range(step - 1)) coords.append(elem.end) # merge to last sub path if first coordinates match if sub_paths: if sub_paths[-1][-1] == coords[0]: sub_paths[-1].extend(coords[1:]) else: sub_paths.append(coords) else: sub_paths.append(coords) for sub_path in sub_paths: path = np.array(sub_path) # transform path += offset_x + 1j * offset_y path.real *= scale_x path.imag *= scale_y lc.append(path) if simplify: mls = lc.as_mls() lc = LineCollection(mls.simplify(tolerance=quantization)) return lc
https://github.com/abey79/vpype/issues/58
Traceback (most recent call last): File "/Users/theuser/.pyenv/versions/plotter/bin/vpype", line 8, in <module> sys.exit(cli()) File "/Users/theuser/.pyenv/versions/3.7.7/envs/plotter/lib/python3.7/site-packages/click/core.py", line 829, in __call__ return self.main(*args, **kwargs) File "/Users/theuser/.pyenv/versions/3.7.7/envs/plotter/lib/python3.7/site-packages/vpype_cli/cli.py", line 72, in main return super().main(args=preprocess_argument_list(args), **extra) File "/Users/theuser/.pyenv/versions/3.7.7/envs/plotter/lib/python3.7/site-packages/click/core.py", line 782, in main rv = self.invoke(ctx) File "/Users/theuser/.pyenv/versions/3.7.7/envs/plotter/lib/python3.7/site-packages/click/core.py", line 1290, in invoke return _process_result(rv) File "/Users/theuser/.pyenv/versions/3.7.7/envs/plotter/lib/python3.7/site-packages/click/core.py", line 1224, in _process_result value = ctx.invoke(self.result_callback, value, **ctx.params) File "/Users/theuser/.pyenv/versions/3.7.7/envs/plotter/lib/python3.7/site-packages/click/core.py", line 610, in invoke return callback(*args, **kwargs) File "/Users/theuser/.pyenv/versions/3.7.7/envs/plotter/lib/python3.7/site-packages/vpype_cli/cli.py", line 118, in process_pipeline execute_processors(processors) File "/Users/theuser/.pyenv/versions/3.7.7/envs/plotter/lib/python3.7/site-packages/vpype_cli/cli.py", line 202, in execute_processors state = proc(state) File "/Users/theuser/.pyenv/versions/3.7.7/envs/plotter/lib/python3.7/site-packages/vpype/decorators.py", line 154, in global_processor state.vector_data = f(state.vector_data, *args, **kwargs) File "/Users/theuser/.pyenv/versions/3.7.7/envs/plotter/lib/python3.7/site-packages/vpype_cli/read.py", line 106, in read read_svg(file, quantization=quantization, simplify=not no_simplify), File "/Users/theuser/.pyenv/versions/3.7.7/envs/plotter/lib/python3.7/site-packages/vpype/io.py", line 163, in read_svg doc.flatten_all_paths(), quantization, scale_x, scale_y, offset_x, offset_y, simplify, File "/Users/theuser/.pyenv/versions/3.7.7/envs/plotter/lib/python3.7/site-packages/svgpathtools/document.py", line 219, in flatten_all_paths path_filter, path_conversions) File "/Users/theuser/.pyenv/versions/3.7.7/envs/plotter/lib/python3.7/site-packages/svgpathtools/document.py", line 142, in flatten_all_paths path = transform(parse_path(converter(path_elem)), path_tf) File "/Users/theuser/.pyenv/versions/3.7.7/envs/plotter/lib/python3.7/site-packages/svgpathtools/parser.py", line 91, in parse_path segments.closed = True File "/Users/theuser/.pyenv/versions/3.7.7/envs/plotter/lib/python3.7/site-packages/svgpathtools/path.py", line 2241, in closed if value and not self._is_closable(): File "/Users/theuser/.pyenv/versions/3.7.7/envs/plotter/lib/python3.7/site-packages/svgpathtools/path.py", line 2219, in _is_closable end = self[-1].end File "/Users/theuser/.pyenv/versions/3.7.7/envs/plotter/lib/python3.7/site-packages/svgpathtools/path.py", line 2081, in __getitem__ return self._segments[index] IndexError: list index out of range
IndexError
def read_svg( filename: str, quantization: float, simplify: bool = False, return_size: bool = False, ) -> Union["LineCollection", Tuple["LineCollection", float, float]]: """Read a SVG file an return its content as a :class:`LineCollection` instance. All curved geometries are chopped in segments no longer than the value of *quantization*. Optionally, the geometries are simplified using Shapely, using the value of *quantization* as tolerance. Args: filename: path of the SVG file quantization: maximum size of segment used to approximate curved geometries simplify: run Shapely's simplify on loaded geometry return_size: if True, return a size 3 Tuple containing the geometries and the SVG width and height Returns: imported geometries, and optionally width and height of the SVG """ doc = svg.Document(filename) width, height, scale_x, scale_y, offset_x, offset_y = _calculate_page_size(doc.root) lc = _convert_flattened_paths( doc.paths(), quantization, scale_x, scale_y, offset_x, offset_y, simplify, ) if return_size: if width is None or height is None: _, _, width, height = lc.bounds() or 0, 0, 0, 0 return lc, width, height else: return lc
def read_svg( filename: str, quantization: float, simplify: bool = False, return_size: bool = False, ) -> Union["LineCollection", Tuple["LineCollection", float, float]]: """Read a SVG file an return its content as a :class:`LineCollection` instance. All curved geometries are chopped in segments no longer than the value of *quantization*. Optionally, the geometries are simplified using Shapely, using the value of *quantization* as tolerance. Args: filename: path of the SVG file quantization: maximum size of segment used to approximate curved geometries simplify: run Shapely's simplify on loaded geometry return_size: if True, return a size 3 Tuple containing the geometries and the SVG width and height Returns: imported geometries, and optionally width and height of the SVG """ doc = svg.Document(filename) width, height, scale_x, scale_y, offset_x, offset_y = _calculate_page_size(doc.root) lc = _convert_flattened_paths( doc.flatten_all_paths(), quantization, scale_x, scale_y, offset_x, offset_y, simplify, ) if return_size: if width is None or height is None: _, _, width, height = lc.bounds() or 0, 0, 0, 0 return lc, width, height else: return lc
https://github.com/abey79/vpype/issues/58
Traceback (most recent call last): File "/Users/theuser/.pyenv/versions/plotter/bin/vpype", line 8, in <module> sys.exit(cli()) File "/Users/theuser/.pyenv/versions/3.7.7/envs/plotter/lib/python3.7/site-packages/click/core.py", line 829, in __call__ return self.main(*args, **kwargs) File "/Users/theuser/.pyenv/versions/3.7.7/envs/plotter/lib/python3.7/site-packages/vpype_cli/cli.py", line 72, in main return super().main(args=preprocess_argument_list(args), **extra) File "/Users/theuser/.pyenv/versions/3.7.7/envs/plotter/lib/python3.7/site-packages/click/core.py", line 782, in main rv = self.invoke(ctx) File "/Users/theuser/.pyenv/versions/3.7.7/envs/plotter/lib/python3.7/site-packages/click/core.py", line 1290, in invoke return _process_result(rv) File "/Users/theuser/.pyenv/versions/3.7.7/envs/plotter/lib/python3.7/site-packages/click/core.py", line 1224, in _process_result value = ctx.invoke(self.result_callback, value, **ctx.params) File "/Users/theuser/.pyenv/versions/3.7.7/envs/plotter/lib/python3.7/site-packages/click/core.py", line 610, in invoke return callback(*args, **kwargs) File "/Users/theuser/.pyenv/versions/3.7.7/envs/plotter/lib/python3.7/site-packages/vpype_cli/cli.py", line 118, in process_pipeline execute_processors(processors) File "/Users/theuser/.pyenv/versions/3.7.7/envs/plotter/lib/python3.7/site-packages/vpype_cli/cli.py", line 202, in execute_processors state = proc(state) File "/Users/theuser/.pyenv/versions/3.7.7/envs/plotter/lib/python3.7/site-packages/vpype/decorators.py", line 154, in global_processor state.vector_data = f(state.vector_data, *args, **kwargs) File "/Users/theuser/.pyenv/versions/3.7.7/envs/plotter/lib/python3.7/site-packages/vpype_cli/read.py", line 106, in read read_svg(file, quantization=quantization, simplify=not no_simplify), File "/Users/theuser/.pyenv/versions/3.7.7/envs/plotter/lib/python3.7/site-packages/vpype/io.py", line 163, in read_svg doc.flatten_all_paths(), quantization, scale_x, scale_y, offset_x, offset_y, simplify, File "/Users/theuser/.pyenv/versions/3.7.7/envs/plotter/lib/python3.7/site-packages/svgpathtools/document.py", line 219, in flatten_all_paths path_filter, path_conversions) File "/Users/theuser/.pyenv/versions/3.7.7/envs/plotter/lib/python3.7/site-packages/svgpathtools/document.py", line 142, in flatten_all_paths path = transform(parse_path(converter(path_elem)), path_tf) File "/Users/theuser/.pyenv/versions/3.7.7/envs/plotter/lib/python3.7/site-packages/svgpathtools/parser.py", line 91, in parse_path segments.closed = True File "/Users/theuser/.pyenv/versions/3.7.7/envs/plotter/lib/python3.7/site-packages/svgpathtools/path.py", line 2241, in closed if value and not self._is_closable(): File "/Users/theuser/.pyenv/versions/3.7.7/envs/plotter/lib/python3.7/site-packages/svgpathtools/path.py", line 2219, in _is_closable end = self[-1].end File "/Users/theuser/.pyenv/versions/3.7.7/envs/plotter/lib/python3.7/site-packages/svgpathtools/path.py", line 2081, in __getitem__ return self._segments[index] IndexError: list index out of range
IndexError
def read_multilayer_svg( filename: str, quantization: float, simplify: bool = False, return_size: bool = False, ) -> Union["VectorData", Tuple["VectorData", float, float]]: """Read a multilayer SVG file and return its content as a :class:`VectorData` instance retaining the SVG's layer structure. Each top-level group is considered a layer. All non-group, top-level elements are imported in layer 1. Groups are matched to layer ID according their `inkscape:label` attribute, their `id` attribute or their appearing order, in that order of priority. Labels are stripped of non-numeric characters and the remaining is used as layer ID. Lacking numeric characters, the appearing order is used. If the label is 0, its changed to 1. All curved geometries are chopped in segments no longer than the value of *quantization*. Optionally, the geometries are simplified using Shapely, using the value of *quantization* as tolerance. Args: filename: path of the SVG file quantization: maximum size of segment used to approximate curved geometries simplify: run Shapely's simplify on loaded geometry return_size: if True, return a size 3 Tuple containing the geometries and the SVG width and height Returns: imported geometries, and optionally width and height of the SVG """ doc = svg.Document(filename) width, height, scale_x, scale_y, offset_x, offset_y = _calculate_page_size(doc.root) vector_data = VectorData() # non-group top level elements are loaded in layer 1 top_level_elements = doc.paths(group_filter=lambda x: x is doc.root) if top_level_elements: vector_data.add( _convert_flattened_paths( top_level_elements, quantization, scale_x, scale_y, offset_x, offset_y, simplify, ), 1, ) for i, g in enumerate(doc.root.iterfind("svg:g", svg.SVG_NAMESPACE)): # compute a decent layer ID lid_str = re.sub( "[^0-9]", "", g.get("{http://www.inkscape.org/namespaces/inkscape}label") or "", ) if not lid_str: lid_str = re.sub("[^0-9]", "", g.get("id") or "") if lid_str: lid = int(lid_str) if lid == 0: lid = 1 else: lid = i + 1 vector_data.add( _convert_flattened_paths( doc.paths_from_group(g, g), quantization, scale_x, scale_y, offset_x, offset_y, simplify, ), lid, ) if return_size: if width is None or height is None: _, _, width, height = vector_data.bounds() or 0, 0, 0, 0 return vector_data, width, height else: return vector_data
def read_multilayer_svg( filename: str, quantization: float, simplify: bool = False, return_size: bool = False, ) -> Union["VectorData", Tuple["VectorData", float, float]]: """Read a multilayer SVG file and return its content as a :class:`VectorData` instance retaining the SVG's layer structure. Each top-level group is considered a layer. All non-group, top-level elements are imported in layer 1. Groups are matched to layer ID according their `inkscape:label` attribute, their `id` attribute or their appearing order, in that order of priority. Labels are stripped of non-numeric characters and the remaining is used as layer ID. Lacking numeric characters, the appearing order is used. If the label is 0, its changed to 1. All curved geometries are chopped in segments no longer than the value of *quantization*. Optionally, the geometries are simplified using Shapely, using the value of *quantization* as tolerance. Args: filename: path of the SVG file quantization: maximum size of segment used to approximate curved geometries simplify: run Shapely's simplify on loaded geometry return_size: if True, return a size 3 Tuple containing the geometries and the SVG width and height Returns: imported geometries, and optionally width and height of the SVG """ doc = svg.Document(filename) width, height, scale_x, scale_y, offset_x, offset_y = _calculate_page_size(doc.root) vector_data = VectorData() # non-group top level elements are loaded in layer 1 top_level_elements = doc.flatten_all_paths(group_filter=lambda x: x is doc.root) if top_level_elements: vector_data.add( _convert_flattened_paths( top_level_elements, quantization, scale_x, scale_y, offset_x, offset_y, simplify, ), 1, ) for i, g in enumerate(doc.root.iterfind("svg:g", SVG_NAMESPACE)): # compute a decent layer ID lid_str = re.sub( "[^0-9]", "", g.get("{http://www.inkscape.org/namespaces/inkscape}label") or "", ) if not lid_str: lid_str = re.sub("[^0-9]", "", g.get("id") or "") if lid_str: lid = int(lid_str) if lid == 0: lid = 1 else: lid = i + 1 vector_data.add( _convert_flattened_paths( flatten_group(g, g), quantization, scale_x, scale_y, offset_x, offset_y, simplify, ), lid, ) if return_size: if width is None or height is None: _, _, width, height = vector_data.bounds() or 0, 0, 0, 0 return vector_data, width, height else: return vector_data
https://github.com/abey79/vpype/issues/58
Traceback (most recent call last): File "/Users/theuser/.pyenv/versions/plotter/bin/vpype", line 8, in <module> sys.exit(cli()) File "/Users/theuser/.pyenv/versions/3.7.7/envs/plotter/lib/python3.7/site-packages/click/core.py", line 829, in __call__ return self.main(*args, **kwargs) File "/Users/theuser/.pyenv/versions/3.7.7/envs/plotter/lib/python3.7/site-packages/vpype_cli/cli.py", line 72, in main return super().main(args=preprocess_argument_list(args), **extra) File "/Users/theuser/.pyenv/versions/3.7.7/envs/plotter/lib/python3.7/site-packages/click/core.py", line 782, in main rv = self.invoke(ctx) File "/Users/theuser/.pyenv/versions/3.7.7/envs/plotter/lib/python3.7/site-packages/click/core.py", line 1290, in invoke return _process_result(rv) File "/Users/theuser/.pyenv/versions/3.7.7/envs/plotter/lib/python3.7/site-packages/click/core.py", line 1224, in _process_result value = ctx.invoke(self.result_callback, value, **ctx.params) File "/Users/theuser/.pyenv/versions/3.7.7/envs/plotter/lib/python3.7/site-packages/click/core.py", line 610, in invoke return callback(*args, **kwargs) File "/Users/theuser/.pyenv/versions/3.7.7/envs/plotter/lib/python3.7/site-packages/vpype_cli/cli.py", line 118, in process_pipeline execute_processors(processors) File "/Users/theuser/.pyenv/versions/3.7.7/envs/plotter/lib/python3.7/site-packages/vpype_cli/cli.py", line 202, in execute_processors state = proc(state) File "/Users/theuser/.pyenv/versions/3.7.7/envs/plotter/lib/python3.7/site-packages/vpype/decorators.py", line 154, in global_processor state.vector_data = f(state.vector_data, *args, **kwargs) File "/Users/theuser/.pyenv/versions/3.7.7/envs/plotter/lib/python3.7/site-packages/vpype_cli/read.py", line 106, in read read_svg(file, quantization=quantization, simplify=not no_simplify), File "/Users/theuser/.pyenv/versions/3.7.7/envs/plotter/lib/python3.7/site-packages/vpype/io.py", line 163, in read_svg doc.flatten_all_paths(), quantization, scale_x, scale_y, offset_x, offset_y, simplify, File "/Users/theuser/.pyenv/versions/3.7.7/envs/plotter/lib/python3.7/site-packages/svgpathtools/document.py", line 219, in flatten_all_paths path_filter, path_conversions) File "/Users/theuser/.pyenv/versions/3.7.7/envs/plotter/lib/python3.7/site-packages/svgpathtools/document.py", line 142, in flatten_all_paths path = transform(parse_path(converter(path_elem)), path_tf) File "/Users/theuser/.pyenv/versions/3.7.7/envs/plotter/lib/python3.7/site-packages/svgpathtools/parser.py", line 91, in parse_path segments.closed = True File "/Users/theuser/.pyenv/versions/3.7.7/envs/plotter/lib/python3.7/site-packages/svgpathtools/path.py", line 2241, in closed if value and not self._is_closable(): File "/Users/theuser/.pyenv/versions/3.7.7/envs/plotter/lib/python3.7/site-packages/svgpathtools/path.py", line 2219, in _is_closable end = self[-1].end File "/Users/theuser/.pyenv/versions/3.7.7/envs/plotter/lib/python3.7/site-packages/svgpathtools/path.py", line 2081, in __getitem__ return self._segments[index] IndexError: list index out of range
IndexError
def _line_to_path(dwg: svgwrite.Drawing, lines: Union[np.ndarray, LineCollection]): """Convert a line into a SVG path element. Accepts either a single line or a :py:class:`LineCollection`. Args: lines: line(s) to convert to path Returns: (svgwrite element): path element """ if isinstance(lines, np.ndarray): lines = [lines] def single_line_to_path(line: np.ndarray) -> str: if line[0] == line[-1] and len(line) > 2: closed = True line = line[:-1] else: closed = False return ( "M" + " L".join(f"{x},{y}" for x, y in as_vector(line)) + (" Z" if closed else "") ) return dwg.path(" ".join(single_line_to_path(line) for line in lines))
def _line_to_path(dwg: svgwrite.Drawing, lines: Union[np.ndarray, LineCollection]): """Convert a line into a SVG path element. Accepts either a single line or a :py:class:`LineCollection`. Args: lines: line(s) to convert to path Returns: (svgwrite element): path element """ if isinstance(lines, np.ndarray): lines = [lines] def single_line_to_path(line: np.ndarray) -> str: if line[0] == line[-1]: closed = True line = line[:-1] else: closed = False return ( "M" + " L".join(f"{x},{y}" for x, y in as_vector(line)) + (" Z" if closed else "") ) return dwg.path(" ".join(single_line_to_path(line) for line in lines))
https://github.com/abey79/vpype/issues/58
Traceback (most recent call last): File "/Users/theuser/.pyenv/versions/plotter/bin/vpype", line 8, in <module> sys.exit(cli()) File "/Users/theuser/.pyenv/versions/3.7.7/envs/plotter/lib/python3.7/site-packages/click/core.py", line 829, in __call__ return self.main(*args, **kwargs) File "/Users/theuser/.pyenv/versions/3.7.7/envs/plotter/lib/python3.7/site-packages/vpype_cli/cli.py", line 72, in main return super().main(args=preprocess_argument_list(args), **extra) File "/Users/theuser/.pyenv/versions/3.7.7/envs/plotter/lib/python3.7/site-packages/click/core.py", line 782, in main rv = self.invoke(ctx) File "/Users/theuser/.pyenv/versions/3.7.7/envs/plotter/lib/python3.7/site-packages/click/core.py", line 1290, in invoke return _process_result(rv) File "/Users/theuser/.pyenv/versions/3.7.7/envs/plotter/lib/python3.7/site-packages/click/core.py", line 1224, in _process_result value = ctx.invoke(self.result_callback, value, **ctx.params) File "/Users/theuser/.pyenv/versions/3.7.7/envs/plotter/lib/python3.7/site-packages/click/core.py", line 610, in invoke return callback(*args, **kwargs) File "/Users/theuser/.pyenv/versions/3.7.7/envs/plotter/lib/python3.7/site-packages/vpype_cli/cli.py", line 118, in process_pipeline execute_processors(processors) File "/Users/theuser/.pyenv/versions/3.7.7/envs/plotter/lib/python3.7/site-packages/vpype_cli/cli.py", line 202, in execute_processors state = proc(state) File "/Users/theuser/.pyenv/versions/3.7.7/envs/plotter/lib/python3.7/site-packages/vpype/decorators.py", line 154, in global_processor state.vector_data = f(state.vector_data, *args, **kwargs) File "/Users/theuser/.pyenv/versions/3.7.7/envs/plotter/lib/python3.7/site-packages/vpype_cli/read.py", line 106, in read read_svg(file, quantization=quantization, simplify=not no_simplify), File "/Users/theuser/.pyenv/versions/3.7.7/envs/plotter/lib/python3.7/site-packages/vpype/io.py", line 163, in read_svg doc.flatten_all_paths(), quantization, scale_x, scale_y, offset_x, offset_y, simplify, File "/Users/theuser/.pyenv/versions/3.7.7/envs/plotter/lib/python3.7/site-packages/svgpathtools/document.py", line 219, in flatten_all_paths path_filter, path_conversions) File "/Users/theuser/.pyenv/versions/3.7.7/envs/plotter/lib/python3.7/site-packages/svgpathtools/document.py", line 142, in flatten_all_paths path = transform(parse_path(converter(path_elem)), path_tf) File "/Users/theuser/.pyenv/versions/3.7.7/envs/plotter/lib/python3.7/site-packages/svgpathtools/parser.py", line 91, in parse_path segments.closed = True File "/Users/theuser/.pyenv/versions/3.7.7/envs/plotter/lib/python3.7/site-packages/svgpathtools/path.py", line 2241, in closed if value and not self._is_closable(): File "/Users/theuser/.pyenv/versions/3.7.7/envs/plotter/lib/python3.7/site-packages/svgpathtools/path.py", line 2219, in _is_closable end = self[-1].end File "/Users/theuser/.pyenv/versions/3.7.7/envs/plotter/lib/python3.7/site-packages/svgpathtools/path.py", line 2081, in __getitem__ return self._segments[index] IndexError: list index out of range
IndexError
def single_line_to_path(line: np.ndarray) -> str: if line[0] == line[-1] and len(line) > 2: closed = True line = line[:-1] else: closed = False return ( "M" + " L".join(f"{x},{y}" for x, y in as_vector(line)) + (" Z" if closed else "") )
def single_line_to_path(line: np.ndarray) -> str: if line[0] == line[-1]: closed = True line = line[:-1] else: closed = False return ( "M" + " L".join(f"{x},{y}" for x, y in as_vector(line)) + (" Z" if closed else "") )
https://github.com/abey79/vpype/issues/58
Traceback (most recent call last): File "/Users/theuser/.pyenv/versions/plotter/bin/vpype", line 8, in <module> sys.exit(cli()) File "/Users/theuser/.pyenv/versions/3.7.7/envs/plotter/lib/python3.7/site-packages/click/core.py", line 829, in __call__ return self.main(*args, **kwargs) File "/Users/theuser/.pyenv/versions/3.7.7/envs/plotter/lib/python3.7/site-packages/vpype_cli/cli.py", line 72, in main return super().main(args=preprocess_argument_list(args), **extra) File "/Users/theuser/.pyenv/versions/3.7.7/envs/plotter/lib/python3.7/site-packages/click/core.py", line 782, in main rv = self.invoke(ctx) File "/Users/theuser/.pyenv/versions/3.7.7/envs/plotter/lib/python3.7/site-packages/click/core.py", line 1290, in invoke return _process_result(rv) File "/Users/theuser/.pyenv/versions/3.7.7/envs/plotter/lib/python3.7/site-packages/click/core.py", line 1224, in _process_result value = ctx.invoke(self.result_callback, value, **ctx.params) File "/Users/theuser/.pyenv/versions/3.7.7/envs/plotter/lib/python3.7/site-packages/click/core.py", line 610, in invoke return callback(*args, **kwargs) File "/Users/theuser/.pyenv/versions/3.7.7/envs/plotter/lib/python3.7/site-packages/vpype_cli/cli.py", line 118, in process_pipeline execute_processors(processors) File "/Users/theuser/.pyenv/versions/3.7.7/envs/plotter/lib/python3.7/site-packages/vpype_cli/cli.py", line 202, in execute_processors state = proc(state) File "/Users/theuser/.pyenv/versions/3.7.7/envs/plotter/lib/python3.7/site-packages/vpype/decorators.py", line 154, in global_processor state.vector_data = f(state.vector_data, *args, **kwargs) File "/Users/theuser/.pyenv/versions/3.7.7/envs/plotter/lib/python3.7/site-packages/vpype_cli/read.py", line 106, in read read_svg(file, quantization=quantization, simplify=not no_simplify), File "/Users/theuser/.pyenv/versions/3.7.7/envs/plotter/lib/python3.7/site-packages/vpype/io.py", line 163, in read_svg doc.flatten_all_paths(), quantization, scale_x, scale_y, offset_x, offset_y, simplify, File "/Users/theuser/.pyenv/versions/3.7.7/envs/plotter/lib/python3.7/site-packages/svgpathtools/document.py", line 219, in flatten_all_paths path_filter, path_conversions) File "/Users/theuser/.pyenv/versions/3.7.7/envs/plotter/lib/python3.7/site-packages/svgpathtools/document.py", line 142, in flatten_all_paths path = transform(parse_path(converter(path_elem)), path_tf) File "/Users/theuser/.pyenv/versions/3.7.7/envs/plotter/lib/python3.7/site-packages/svgpathtools/parser.py", line 91, in parse_path segments.closed = True File "/Users/theuser/.pyenv/versions/3.7.7/envs/plotter/lib/python3.7/site-packages/svgpathtools/path.py", line 2241, in closed if value and not self._is_closable(): File "/Users/theuser/.pyenv/versions/3.7.7/envs/plotter/lib/python3.7/site-packages/svgpathtools/path.py", line 2219, in _is_closable end = self[-1].end File "/Users/theuser/.pyenv/versions/3.7.7/envs/plotter/lib/python3.7/site-packages/svgpathtools/path.py", line 2081, in __getitem__ return self._segments[index] IndexError: list index out of range
IndexError
def parseImageBookmark(page): imageList = list() image_bookmark = json.loads(page) for work in image_bookmark["body"]["works"]: if "isAdContainer" in work and work["isAdContainer"]: continue # Issue #822 if "illustId" in work: imageList.append(int(work["illustId"])) elif "id" in work: imageList.append(int(work["id"])) # temp = page.find('ul', attrs={'class': PixivBookmark.__re_imageULItemsClass}) # temp = temp.findAll('a') # if temp is None or len(temp) == 0: # return imageList # for item in temp: # href = re.search(r'/artworks/(\d+)', str(item)) # if href is not None: # href = href.group(1) # if not int(href) in imageList: # imageList.append(int(href)) return imageList
def parseImageBookmark(page): imageList = list() image_bookmark = json.loads(page) for work in image_bookmark["body"]["works"]: if "isAdContainer" in work and work["isAdContainer"]: continue imageList.append(int(work["illustId"])) # temp = page.find('ul', attrs={'class': PixivBookmark.__re_imageULItemsClass}) # temp = temp.findAll('a') # if temp is None or len(temp) == 0: # return imageList # for item in temp: # href = re.search(r'/artworks/(\d+)', str(item)) # if href is not None: # href = href.group(1) # if not int(href) in imageList: # imageList.append(int(href)) return imageList
https://github.com/Nandaka/PixivUtil2/issues/822
Importing image bookmarks... Importing user's bookmarked image from page 1 Source URL: https://www.pixiv.net/ajax/user/XXXXXXXX/illusts/bookmarks?tag=&amp;offset=0&amp;limit=48&amp;rest=show Error at process_image_bookmark(): (<class 'KeyError'>, KeyError('illustId'), <traceback object at 0x044FB988>) Traceback (most recent call last): File "PixivUtil2.py", line 1252, in main File "PixivUtil2.py", line 964, in main_loop File "PixivUtil2.py", line 520, in menu_download_from_online_image_bookmark File "PixivBookmarkHandler.pyc", line 73, in process_image_bookmark File "PixivBookmarkHandler.pyc", line 342, in get_image_bookmark File "PixivBookmark.pyc", line 64, in parseImageBookmark KeyError: 'illustId'
KeyError
def sanitize_filename(name, rootDir=None): """Replace reserved character/name with underscore (windows), rootDir is not sanitized.""" # get the absolute rootdir if rootDir is not None: rootDir = os.path.abspath(rootDir) # Unescape '&amp;', '&lt;', and '&gt;' name = html.unescape(name) name = __badchars__.sub("_", name) # Remove unicode control characters name = "".join(c for c in name if unicodedata.category(c) != "Cc") # Strip leading/trailing space for each directory # Issue #627: remove trailing '.' # Ensure Windows reserved filenames are prefixed with _ stripped_name = list() for item in name.split(os.sep): if Path(item).is_reserved(): item = "_" + item stripped_name.append(item.strip(" .\t\r\n")) name = os.sep.join(stripped_name) if platform.system() == "Windows": # cut whole path to 255 char # TODO: check for Windows long path extensions being enabled if rootDir is not None: # need to remove \\ from name prefix tname = name[1:] if name[0] == "\\" else name full_name = os.path.abspath(os.path.join(rootDir, tname)) else: full_name = os.path.abspath(name) if len(full_name) > 255: filename, extname = os.path.splitext( name ) # NOT full_name, to avoid clobbering paths # don't trim the extension name = filename[: 255 - len(extname)] + extname if name == extname: # we have no file name left raise OSError( None, "Path name too long", full_name, 0x000000A1 ) # 0xA1 is "invalid path" else: # Unix: cut filename to <= 249 bytes # TODO: allow macOS higher limits, HFS+ allows 255 UTF-16 chars, and APFS 255 UTF-8 chars while len(name.encode("utf-8")) > 249: filename, extname = os.path.splitext(name) name = filename[: len(filename) - 1] + extname if rootDir is not None: name = name[1:] if name[0] == "\\" else name # name = os.path.abspath(os.path.join(rootDir, name)) # compatibility... name = rootDir + os.sep + name get_logger().debug("Sanitized Filename: %s", name) return name
def sanitize_filename(name, rootDir=None): """Replace reserved character/name with underscore (windows), rootDir is not sanitized.""" # get the absolute rootdir if rootDir is not None: rootDir = os.path.abspath(rootDir) # Unescape '&amp;', '&lt;', and '&gt;' name = html.unescape(name) name = __badchars__.sub("_", name) # Remove unicode control characters name = "".join(c for c in name if unicodedata.category(c) != "Cc") # Strip leading/trailing space for each directory # Issue #627: remove trailing '.' # Ensure Windows reserved filenames are prefixed with _ stripped_name = list() for item in name.split(os.sep): if Path(item).is_reserved(): item = "_" + item stripped_name.append(item.strip(" .\t\r\n")) name = os.sep.join(stripped_name) if platform.system() == "Windows": # cut whole path to 255 char # TODO: check for Windows long path extensions being enabled if rootDir is not None: # need to remove \\ from name prefix tname = name[1:] if name[0] == "\\" else name full_name = os.path.abspath(os.path.join(rootDir, tname)) else: full_name = os.path.abspath(name) if len(full_name) > 255: filename, extname = os.path.splitext( name ) # NOT full_name, to avoid clobbering paths # don't trim the extension name = filename[: 255 - len(extname)] + extname if name == extname: # we have no file name left raise OSError( None, "Path name too long", full_name, 0x000000A1 ) # 0xA1 is "invalid path" else: # Unix: cut filename to <= 249 bytes # TODO: allow macOS higher limits, HFS+ allows 255 UTF-16 chars, and APFS 255 UTF-8 chars while len(name.encode("utf-8")) > 249: filename, extname = os.path.splitext(name) name = filename[: len(filename) - 1] + extname if rootDir is not None: name = name[1:] if name[0] == "\\" else name name = os.path.abspath(os.path.join(rootDir, name)) get_logger().debug("Sanitized Filename: %s", name) return name
https://github.com/Nandaka/PixivUtil2/issues/663
Member Background : no_background Processing images from 1 to 16 of 16 Traceback (most recent call last): File "PixivUtil2.py", line 492, in process_member download_image(artist.artistAvatar, File "PixivUtil2.py", line 137, in download_image test_utf = open(filename_test + '.test', "wb") PermissionError: [Errno 13] Permission denied: '//γ‚γ„γ†γˆγŠ.test' Error at process_member(): (<class 'PermissionError'>, PermissionError(13, 'Permission denied'), <traceback object at 0x74b92488>) Dumping html to: Error page for member 31040169 at page 1.html Traceback (most recent call last): File "PixivUtil2.py", line 2474, in main np_is_valid, op_is_valid, selection = main_loop(ewd, op_is_valid, selection, np_is_valid, args) File "PixivUtil2.py", line 2172, in main_loop menu_download_by_member_id(op_is_valid, args) File "PixivUtil2.py", line 1558, in menu_download_by_member_id process_member(member_id, page=page, end_page=end_page, title_prefix=prefix) File "PixivUtil2.py", line 492, in process_member download_image(artist.artistAvatar, File "PixivUtil2.py", line 137, in download_image test_utf = open(filename_test + '.test', "wb") PermissionError: [Errno 13] Permission denied: '//γ‚γ„γ†γˆγŠ.test' press enter to exit.
PermissionError
def sanitize_filename(name, rootDir=None): """Replace reserved character/name with underscore (windows), rootDir is not sanitized.""" # get the absolute rootdir if rootDir is not None: rootDir = os.path.abspath(rootDir) # Unescape '&amp;', '&lt;', and '&gt;' name = html.unescape(name) name = __badchars__.sub("_", name) # Remove unicode control characters name = "".join(c for c in name if unicodedata.category(c) != "Cc") # Strip leading/trailing space for each directory # Issue #627: remove trailing '.' # Ensure Windows reserved filenames are prefixed with _ stripped_name = list() for item in name.split(os.sep): if Path(item).is_reserved(): item = "_" + item stripped_name.append(item.strip(" .\t\r\n")) name = os.sep.join(stripped_name) if platform.system() == "Windows": # cut whole path to 255 char # TODO: check for Windows long path extensions being enabled if rootDir is not None: # need to remove \\ from name prefix tname = name[1:] if name[0] == os.sep else name full_name = os.path.abspath(os.path.join(rootDir, tname)) else: full_name = os.path.abspath(name) if len(full_name) > 255: filename, extname = os.path.splitext( name ) # NOT full_name, to avoid clobbering paths # don't trim the extension name = filename[: 255 - len(extname)] + extname if name == extname: # we have no file name left raise OSError( None, "Path name too long", full_name, 0x000000A1 ) # 0xA1 is "invalid path" else: # Unix: cut filename to <= 249 bytes # TODO: allow macOS higher limits, HFS+ allows 255 UTF-16 chars, and APFS 255 UTF-8 chars while len(name.encode("utf-8")) > 249: filename, extname = os.path.splitext(name) name = filename[: len(filename) - 1] + extname if rootDir is not None: name = name[1:] if name[0] == os.sep else name name = os.path.abspath(os.path.join(rootDir, name)) get_logger().debug("Sanitized Filename: %s", name) return name
def sanitize_filename(name, rootDir=None): """Replace reserved character/name with underscore (windows), rootDir is not sanitized.""" # get the absolute rootdir if rootDir is not None: rootDir = os.path.abspath(rootDir) # Unescape '&amp;', '&lt;', and '&gt;' name = html.unescape(name) name = __badchars__.sub("_", name) # Remove unicode control characters name = "".join(c for c in name if unicodedata.category(c) != "Cc") # Strip leading/trailing space for each directory # Issue #627: remove trailing '.' # Ensure Windows reserved filenames are prefixed with _ stripped_name = list() for item in name.split(os.sep): if Path(item).is_reserved(): item = "_" + item stripped_name.append(item.strip(" .\t\r\n")) name = os.sep.join(stripped_name) if platform.system() == "Windows": # cut whole path to 255 char # TODO: check for Windows long path extensions being enabled if rootDir is not None: # need to remove \\ from name prefix tname = name[1:] if name[0] == "\\" else name full_name = os.path.abspath(os.path.join(rootDir, tname)) else: full_name = os.path.abspath(name) if len(full_name) > 255: filename, extname = os.path.splitext( name ) # NOT full_name, to avoid clobbering paths # don't trim the extension name = filename[: 255 - len(extname)] + extname if name == extname: # we have no file name left raise OSError( None, "Path name too long", full_name, 0x000000A1 ) # 0xA1 is "invalid path" else: # Unix: cut filename to <= 249 bytes # TODO: allow macOS higher limits, HFS+ allows 255 UTF-16 chars, and APFS 255 UTF-8 chars while len(name.encode("utf-8")) > 249: filename, extname = os.path.splitext(name) name = filename[: len(filename) - 1] + extname if rootDir is not None: name = name[1:] if name[0] == "\\" else name # name = os.path.abspath(os.path.join(rootDir, name)) # compatibility... name = rootDir + os.sep + name get_logger().debug("Sanitized Filename: %s", name) return name
https://github.com/Nandaka/PixivUtil2/issues/663
Member Background : no_background Processing images from 1 to 16 of 16 Traceback (most recent call last): File "PixivUtil2.py", line 492, in process_member download_image(artist.artistAvatar, File "PixivUtil2.py", line 137, in download_image test_utf = open(filename_test + '.test', "wb") PermissionError: [Errno 13] Permission denied: '//γ‚γ„γ†γˆγŠ.test' Error at process_member(): (<class 'PermissionError'>, PermissionError(13, 'Permission denied'), <traceback object at 0x74b92488>) Dumping html to: Error page for member 31040169 at page 1.html Traceback (most recent call last): File "PixivUtil2.py", line 2474, in main np_is_valid, op_is_valid, selection = main_loop(ewd, op_is_valid, selection, np_is_valid, args) File "PixivUtil2.py", line 2172, in main_loop menu_download_by_member_id(op_is_valid, args) File "PixivUtil2.py", line 1558, in menu_download_by_member_id process_member(member_id, page=page, end_page=end_page, title_prefix=prefix) File "PixivUtil2.py", line 492, in process_member download_image(artist.artistAvatar, File "PixivUtil2.py", line 137, in download_image test_utf = open(filename_test + '.test', "wb") PermissionError: [Errno 13] Permission denied: '//γ‚γ„γ†γˆγŠ.test' press enter to exit.
PermissionError
def parseBookmark(page, root_directory, db_path, locale="en", is_json=False): """Parse favorite artist page""" from PixivDBManager import PixivDBManager bookmarks = list() result2 = list() db = PixivDBManager(root_directory=root_directory, target=db_path) if is_json: parsed = json.loads(page) for member in parsed["body"]["users"]: if "isAdContainer" in member and member["isAdContainer"]: continue result2.append(member["userId"]) else: # old method parse_page = BeautifulSoup(page, features="html5lib") __re_member = re.compile(locale + r"/users/(\d*)") member_list = parse_page.find(attrs={"class": "members"}) result = member_list.findAll("a") # filter duplicated member_id d = collections.OrderedDict() for r in result: member_id = __re_member.findall(r["href"]) if len(member_id) > 0: d[member_id[0]] = member_id[0] result2 = list(d.keys()) parse_page.decompose() del parse_page for r in result2: item = db.selectMemberByMemberId2(r) bookmarks.append(item) return bookmarks
def parseBookmark(page, root_directory, db_path, locale="en", is_json=False): """Parse favorite artist page""" from PixivDBManager import PixivDBManager bookmarks = list() result2 = list() db = PixivDBManager(root_directory=root_directory, target=db_path) if is_json: parsed = json.loads(page) for member in parsed["body"]["users"]: result2.append(member["userId"]) else: # old method parse_page = BeautifulSoup(page, features="html5lib") __re_member = re.compile(locale + r"/users/(\d*)") member_list = parse_page.find(attrs={"class": "members"}) result = member_list.findAll("a") # filter duplicated member_id d = collections.OrderedDict() for r in result: member_id = __re_member.findall(r["href"]) if len(member_id) > 0: d[member_id[0]] = member_id[0] result2 = list(d.keys()) parse_page.decompose() del parse_page for r in result2: item = db.selectMemberByMemberId2(r) bookmarks.append(item) return bookmarks
https://github.com/Nandaka/PixivUtil2/issues/622
Input: 5 Include Private bookmarks [y/n/o]: Start Page (default=1): End Page (default=0, 0 for no limit): Importing Bookmarks... Exporting page 1 Source URL: https://www.pixiv.net/bookmark.php?type=user&amp;p=1 Using default DB Path: /mnt/c/PixivUtil2/db.sqlite No more data Result: 0 items. Error at process_bookmark(): (<class 'ZeroDivisionError'>, ZeroDivisionError('float division by zero'), <traceback object at 0x7fa7885a55a0>) Traceback (most recent call last): File "PixivUtil2.py", line 2407, in main np_is_valid, op_is_valid, selection = main_loop(ewd, op_is_valid, selection, np_is_valid, args) File "PixivUtil2.py", line 2127, in main_loop menu_download_from_online_user_bookmark(op_is_valid, args) File "PixivUtil2.py", line 1722, in menu_download_from_online_user_bookmark process_bookmark(hide, start_page, end_page) File "PixivUtil2.py", line 1235, in process_bookmark print("%d/%d\t%f %%" % (i, len(total_list), 100.0 * i / float(len(total_list)))) ZeroDivisionError: float division by zero press enter to exit.
ZeroDivisionError
def parseImageBookmark(page): imageList = list() image_bookmark = json.loads(page) for work in image_bookmark["body"]["works"]: if "isAdContainer" in work and work["isAdContainer"]: continue imageList.append(work["illustId"]) # temp = page.find('ul', attrs={'class': PixivBookmark.__re_imageULItemsClass}) # temp = temp.findAll('a') # if temp is None or len(temp) == 0: # return imageList # for item in temp: # href = re.search(r'/artworks/(\d+)', str(item)) # if href is not None: # href = href.group(1) # if not int(href) in imageList: # imageList.append(int(href)) return imageList
def parseImageBookmark(page): imageList = list() temp = page.find("ul", attrs={"class": PixivBookmark.__re_imageULItemsClass}) temp = temp.findAll("a") if temp is None or len(temp) == 0: return imageList for item in temp: href = re.search(r"/artworks/(\d+)", str(item)) if href is not None: href = href.group(1) if not int(href) in imageList: imageList.append(int(href)) return imageList
https://github.com/Nandaka/PixivUtil2/issues/622
Input: 5 Include Private bookmarks [y/n/o]: Start Page (default=1): End Page (default=0, 0 for no limit): Importing Bookmarks... Exporting page 1 Source URL: https://www.pixiv.net/bookmark.php?type=user&amp;p=1 Using default DB Path: /mnt/c/PixivUtil2/db.sqlite No more data Result: 0 items. Error at process_bookmark(): (<class 'ZeroDivisionError'>, ZeroDivisionError('float division by zero'), <traceback object at 0x7fa7885a55a0>) Traceback (most recent call last): File "PixivUtil2.py", line 2407, in main np_is_valid, op_is_valid, selection = main_loop(ewd, op_is_valid, selection, np_is_valid, args) File "PixivUtil2.py", line 2127, in main_loop menu_download_from_online_user_bookmark(op_is_valid, args) File "PixivUtil2.py", line 1722, in menu_download_from_online_user_bookmark process_bookmark(hide, start_page, end_page) File "PixivUtil2.py", line 1235, in process_bookmark print("%d/%d\t%f %%" % (i, len(total_list), 100.0 * i / float(len(total_list)))) ZeroDivisionError: float division by zero press enter to exit.
ZeroDivisionError
def get_image_bookmark(hide, start_page=1, end_page=0, tag="", sorting=None): """Get user's image bookmark""" total_list = list() i = start_page offset = 0 limit = 48 member_id = __br__._myId while True: if end_page != 0 and i > end_page: print("Page Limit reached: " + str(end_page)) break # https://www.pixiv.net/ajax/user/189816/illusts/bookmarks?tag=&offset=0&limit=48&rest=show show = "show" if hide: show = "hide" # # Implement #468 default is desc, only for your own bookmark. # not available in current api # if sorting in ('asc', 'date_d', 'date'): # url = url + "&order=" + sorting if tag is not None and len(tag) > 0: tag = PixivHelper.encode_tags(tag) offset = limit * (i - 1) url = f"https://www.pixiv.net/ajax/user/{member_id}/illusts/bookmarks?tag={tag}&offset={offset}&limit={limit}&rest={show}" PixivHelper.print_and_log( "info", f"Importing user's bookmarked image from page {i}" ) PixivHelper.print_and_log("info", f"Source URL: {url}") page = __br__.open(url) page_str = page.read().decode("utf8") page.close() bookmarks = PixivBookmark.parseImageBookmark(page_str) total_list.extend(bookmarks) if len(bookmarks) == 0: print("No more images.") break else: print(" found " + str(len(bookmarks)) + " images.") i = i + 1 # Issue#569 wait() return total_list
def get_image_bookmark(hide, start_page=1, end_page=0, tag="", sorting=None): """Get user's image bookmark""" total_list = list() i = start_page while True: if end_page != 0 and i > end_page: print("Page Limit reached: " + str(end_page)) break url = "https://www.pixiv.net/bookmark.php?p=" + str(i) if hide: url = url + "&rest=hide" # Implement #468 default is desc, only for your own bookmark. if sorting in ("asc", "date_d", "date"): url = url + "&order=" + sorting if tag is not None and len(tag) > 0: url = url + "&tag=" + PixivHelper.encode_tags(tag) PixivHelper.print_and_log( "info", "Importing user's bookmarked image from page " + str(i) ) PixivHelper.print_and_log("info", "Source URL: " + url) page = __br__.open(url) parse_page = BeautifulSoup(page.read().decode("utf-8"), features="html5lib") bookmarks = PixivBookmark.parseImageBookmark(parse_page) total_list.extend(bookmarks) if len(bookmarks) == 0: print("No more images.") break else: print(" found " + str(len(bookmarks)) + " images.") i = i + 1 page.close() parse_page.decompose() del parse_page # Issue#569 wait() return total_list
https://github.com/Nandaka/PixivUtil2/issues/622
Input: 5 Include Private bookmarks [y/n/o]: Start Page (default=1): End Page (default=0, 0 for no limit): Importing Bookmarks... Exporting page 1 Source URL: https://www.pixiv.net/bookmark.php?type=user&amp;p=1 Using default DB Path: /mnt/c/PixivUtil2/db.sqlite No more data Result: 0 items. Error at process_bookmark(): (<class 'ZeroDivisionError'>, ZeroDivisionError('float division by zero'), <traceback object at 0x7fa7885a55a0>) Traceback (most recent call last): File "PixivUtil2.py", line 2407, in main np_is_valid, op_is_valid, selection = main_loop(ewd, op_is_valid, selection, np_is_valid, args) File "PixivUtil2.py", line 2127, in main_loop menu_download_from_online_user_bookmark(op_is_valid, args) File "PixivUtil2.py", line 1722, in menu_download_from_online_user_bookmark process_bookmark(hide, start_page, end_page) File "PixivUtil2.py", line 1235, in process_bookmark print("%d/%d\t%f %%" % (i, len(total_list), 100.0 * i / float(len(total_list)))) ZeroDivisionError: float division by zero press enter to exit.
ZeroDivisionError
def get_bookmarks(hide, start_page=1, end_page=0, member_id=None): """Get User's bookmarked artists""" total_list = list() i = start_page limit = 24 offset = 0 is_json = False while True: if end_page != 0 and i > end_page: print("Limit reached") break PixivHelper.print_and_log("info", f"Exporting page {i}") if member_id: is_json = True offset = limit * (i - 1) url = f"https://www.pixiv.net/ajax/user/{member_id}/following?offset={offset}&limit={limit}" else: url = f"https://www.pixiv.net/bookmark.php?type=user&p={i}" if hide: url = url + "&rest=hide" else: url = url + "&rest=show" PixivHelper.print_and_log("info", f"Source URL: {url}") page = __br__.open_with_retry(url) page_str = page.read().decode("utf8") page.close() bookmarks = PixivBookmark.parseBookmark( page_str, root_directory=__config__.rootDirectory, db_path=__config__.dbPath, is_json=is_json, ) if len(bookmarks) == 0: print("No more data") break total_list.extend(bookmarks) i = i + 1 print(str(len(bookmarks)), "items") wait() return total_list
def get_bookmarks(hide, start_page=1, end_page=0, member_id=None): """Get User's bookmarked artists""" total_list = list() i = start_page limit = 24 offset = 0 is_json = False while True: if end_page != 0 and i > end_page: print("Limit reached") break PixivHelper.print_and_log("info", f"Exporting page {i}") if member_id: is_json = True offset = 24 * (i - 1) url = f"https://www.pixiv.net/ajax/user/{member_id}/following?offset={offset}&limit={limit}" else: url = f"https://www.pixiv.net/bookmark.php?type=user&p={i}" if hide: url = url + "&rest=hide" else: url = url + "&rest=show" PixivHelper.print_and_log("info", f"Source URL: {url}") page = __br__.open_with_retry(url) page_str = page.read().decode("utf8") page.close() bookmarks = PixivBookmark.parseBookmark( page_str, root_directory=__config__.rootDirectory, db_path=__config__.dbPath, is_json=is_json, ) if len(bookmarks) == 0: print("No more data") break total_list.extend(bookmarks) i = i + 1 print(str(len(bookmarks)), "items") wait() return total_list
https://github.com/Nandaka/PixivUtil2/issues/622
Input: 5 Include Private bookmarks [y/n/o]: Start Page (default=1): End Page (default=0, 0 for no limit): Importing Bookmarks... Exporting page 1 Source URL: https://www.pixiv.net/bookmark.php?type=user&amp;p=1 Using default DB Path: /mnt/c/PixivUtil2/db.sqlite No more data Result: 0 items. Error at process_bookmark(): (<class 'ZeroDivisionError'>, ZeroDivisionError('float division by zero'), <traceback object at 0x7fa7885a55a0>) Traceback (most recent call last): File "PixivUtil2.py", line 2407, in main np_is_valid, op_is_valid, selection = main_loop(ewd, op_is_valid, selection, np_is_valid, args) File "PixivUtil2.py", line 2127, in main_loop menu_download_from_online_user_bookmark(op_is_valid, args) File "PixivUtil2.py", line 1722, in menu_download_from_online_user_bookmark process_bookmark(hide, start_page, end_page) File "PixivUtil2.py", line 1235, in process_bookmark print("%d/%d\t%f %%" % (i, len(total_list), 100.0 * i / float(len(total_list)))) ZeroDivisionError: float division by zero press enter to exit.
ZeroDivisionError
def menu_download_from_online_image_bookmark(opisvalid, args): __log__.info("User's Image Bookmark mode.") start_page = 1 end_page = 0 hide = "n" tag = "" sorting = "desc" if opisvalid and len(args) > 0: hide = args[0].lower() if hide not in ("y", "n", "o"): print("Invalid args: ", args) return (start_page, end_page) = get_start_and_end_number_from_args(args, offset=1) if len(args) > 3: tag = args[3] if len(args) > 4: sorting = args[4].lower() if sorting not in ("asc", "desc", "date", "date_d"): print("Invalid sorting order: ", sorting) return else: hide = input("Include Private bookmarks [y/n/o]: ").rstrip("\r") or "n" hide = hide.lower() if hide not in ("y", "n", "o"): print("Invalid args: ", hide) return tag = input("Tag (default=All Images): ").rstrip("\r") or "" (start_page, end_page) = get_start_and_end_number() # sorting = input("Sort Order [asc/desc/date/date_d]: ").rstrip("\r") or 'desc' # sorting = sorting.lower() # if sorting not in ('asc', 'desc', 'date', 'date_d'): # print("Invalid sorting order: ", sorting) # return process_image_bookmark(hide, start_page, end_page, tag, sorting)
def menu_download_from_online_image_bookmark(opisvalid, args): __log__.info("User's Image Bookmark mode.") start_page = 1 end_page = 0 hide = "n" tag = "" sorting = "desc" if opisvalid and len(args) > 0: hide = args[0].lower() if hide not in ("y", "n", "o"): print("Invalid args: ", args) return (start_page, end_page) = get_start_and_end_number_from_args(args, offset=1) if len(args) > 3: tag = args[3] if len(args) > 4: sorting = args[4].lower() if sorting not in ("asc", "desc", "date", "date_d"): print("Invalid sorting order: ", sorting) return else: hide = input("Include Private bookmarks [y/n/o]: ").rstrip("\r") or "n" hide = hide.lower() if hide not in ("y", "n", "o"): print("Invalid args: ", hide) return tag = input("Tag (default=All Images): ").rstrip("\r") or "" (start_page, end_page) = get_start_and_end_number() sorting = input("Sort Order [asc/desc/date/date_d]: ").rstrip("\r") or "desc" sorting = sorting.lower() if sorting not in ("asc", "desc", "date", "date_d"): print("Invalid sorting order: ", sorting) return process_image_bookmark(hide, start_page, end_page, tag, sorting)
https://github.com/Nandaka/PixivUtil2/issues/622
Input: 5 Include Private bookmarks [y/n/o]: Start Page (default=1): End Page (default=0, 0 for no limit): Importing Bookmarks... Exporting page 1 Source URL: https://www.pixiv.net/bookmark.php?type=user&amp;p=1 Using default DB Path: /mnt/c/PixivUtil2/db.sqlite No more data Result: 0 items. Error at process_bookmark(): (<class 'ZeroDivisionError'>, ZeroDivisionError('float division by zero'), <traceback object at 0x7fa7885a55a0>) Traceback (most recent call last): File "PixivUtil2.py", line 2407, in main np_is_valid, op_is_valid, selection = main_loop(ewd, op_is_valid, selection, np_is_valid, args) File "PixivUtil2.py", line 2127, in main_loop menu_download_from_online_user_bookmark(op_is_valid, args) File "PixivUtil2.py", line 1722, in menu_download_from_online_user_bookmark process_bookmark(hide, start_page, end_page) File "PixivUtil2.py", line 1235, in process_bookmark print("%d/%d\t%f %%" % (i, len(total_list), 100.0 * i / float(len(total_list)))) ZeroDivisionError: float division by zero press enter to exit.
ZeroDivisionError