• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

Python nodes.MypyFile类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Python中mypy.nodes.MypyFile的典型用法代码示例。如果您正苦于以下问题:Python MypyFile类的具体用法?Python MypyFile怎么用?Python MypyFile使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。



在下文中一共展示了MypyFile类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。

示例1: get_dependencies

def get_dependencies(target: MypyFile,
                     type_map: Dict[Expression, Type],
                     python_version: Tuple[int, int]) -> Dict[str, Set[str]]:
    """Get all dependencies of a node, recursively."""
    visitor = DependencyVisitor(type_map, python_version, target.alias_deps)
    target.accept(visitor)
    return visitor.map
开发者ID:sixolet,项目名称:mypy,代码行数:7,代码来源:deps.py


示例2: merge_asts

def merge_asts(old: MypyFile, old_symbols: SymbolTable,
               new: MypyFile, new_symbols: SymbolTable) -> None:
    """Merge a new version of a module AST to a previous version.

    The main idea is to preserve the identities of externally visible
    nodes in the old AST (that have a corresponding node in the new AST).
    All old node state (outside identity) will come from the new AST.

    When this returns, 'old' will refer to the merged AST, but 'new_symbols'
    will be the new symbol table. 'new' and 'old_symbols' will no longer be
    valid.
    """
    assert new.fullname() == old.fullname()
    # Find the mapping from new to old node identities for all nodes
    # whose identities should be preserved.
    replacement_map = replacement_map_from_symbol_table(
        old_symbols, new_symbols, prefix=old.fullname())
    # Also replace references to the new MypyFile node.
    replacement_map[new] = old
    # Perform replacements to everywhere within the new AST (not including symbol
    # tables).
    node = replace_nodes_in_ast(new, replacement_map)
    assert node is old
    # Also replace AST node references in the *new* symbol table (we'll
    # continue to use the new symbol table since it has all the new definitions
    # that have no correspondence in the old AST).
    replace_nodes_in_symbol_table(new_symbols, replacement_map)
开发者ID:python,项目名称:mypy,代码行数:27,代码来源:astmerge.py


示例3: strip_file_top_level

 def strip_file_top_level(self, file_node: MypyFile) -> None:
     """Strip a module top-level (don't recursive into functions)."""
     self.names = file_node.names
     self.file_node = file_node
     self.recurse_into_functions = False
     file_node.plugin_deps.clear()
     file_node.accept(self)
开发者ID:Michael0x2a,项目名称:mypy,代码行数:7,代码来源:aststrip.py


示例4: on_file

    def on_file(self, tree: MypyFile, type_map: Dict[Expression, Type]) -> None:
        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 tokenize.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)
开发者ID:alexandrul,项目名称:mypy,代码行数:34,代码来源:report.py


示例5: on_file

    def on_file(self,
                tree: MypyFile,
                type_map: Dict[Expression, Type],
                options: Options) -> None:
        path = os.path.relpath(tree.path)
        visitor = stats.StatisticsVisitor(inferred=True, filename=tree.fullname(),
                                          typemap=type_map, all_nodes=True)
        tree.accept(visitor)

        class_name = os.path.basename(path)
        file_info = FileInfo(path, tree._fullname)
        class_element = etree.Element('class',
                                      filename=path,
                                      complexity='1.0',
                                      name=class_name)
        etree.SubElement(class_element, 'methods')
        lines_element = etree.SubElement(class_element, 'lines')

        with tokenize.open(path) as input_file:
            class_lines_covered = 0
            class_total_lines = 0
            for lineno, _ in enumerate(input_file, 1):
                status = visitor.line_map.get(lineno, stats.TYPE_EMPTY)
                hits = 0
                branch = False
                if status == stats.TYPE_EMPTY:
                    continue
                class_total_lines += 1
                if status != stats.TYPE_ANY:
                    class_lines_covered += 1
                    hits = 1
                if status == stats.TYPE_IMPRECISE:
                    branch = True
                file_info.counts[status] += 1
                line_element = etree.SubElement(lines_element, 'line',
                                                number=str(lineno),
                                                precision=stats.precision_names[status],
                                                hits=str(hits),
                                                branch=str(branch).lower())
                if branch:
                    line_element.attrib['condition-coverage'] = '50% (1/2)'
            class_element.attrib['branch-rate'] = '0'
            class_element.attrib['line-rate'] = get_line_rate(class_lines_covered,
                                                              class_total_lines)
            # parent_module is set to whichever module contains this file.  For most files, we want
            # to simply strip the last element off of the module.  But for __init__.py files,
            # the module == the parent module.
            parent_module = file_info.module.rsplit('.', 1)[0]
            if file_info.name.endswith('__init__.py'):
                parent_module = file_info.module

            if parent_module not in self.root_package.packages:
                self.root_package.packages[parent_module] = CoberturaPackage(parent_module)
            current_package = self.root_package.packages[parent_module]
            packages_to_update = [self.root_package, current_package]
            for package in packages_to_update:
                package.total_lines += class_total_lines
                package.covered_lines += class_lines_covered
            current_package.classes[class_name] = class_element
开发者ID:chadrik,项目名称:mypy,代码行数:59,代码来源:report.py


示例6: visit_mypy_file

 def visit_mypy_file(self, o: MypyFile) -> None:
     self.scope.enter_file(o.fullname())
     self.is_package_init_file = o.is_package_init_file()
     self.add_type_alias_deps(self.scope.current_target())
     for trigger, targets in o.plugin_deps.items():
         self.map.setdefault(trigger, set()).update(targets)
     super().visit_mypy_file(o)
     self.scope.leave()
开发者ID:Michael0x2a,项目名称:mypy,代码行数:8,代码来源:deps.py


示例7: visit_mypy_file

 def visit_mypy_file(self, node: MypyFile) -> Node:
     # NOTE: The 'names' and 'imports' instance variables will be empty!
     new = MypyFile(self.nodes(node.defs), [], node.is_bom)
     new._name = node._name
     new._fullname = node._fullname
     new.path = node.path
     new.names = SymbolTable()
     return new
开发者ID:akaihola,项目名称:mypy,代码行数:8,代码来源:treetransform.py


示例8: visit_mypy_file

 def visit_mypy_file(self, node: MypyFile) -> MypyFile:
     # NOTE: The 'names' and 'imports' instance variables will be empty!
     new = MypyFile(self.statements(node.defs), [], node.is_bom,
                    ignored_lines=set(node.ignored_lines))
     new._fullname = node._fullname
     new.path = node.path
     new.names = SymbolTable()
     return new
开发者ID:chadrik,项目名称:mypy,代码行数:8,代码来源:treetransform.py


示例9: find_classes

def find_classes(node: MypyFile) -> Set[str]:
    results = set()  # type: Set[str]

    class ClassTraverser(mypy.traverser.TraverserVisitor):
        def visit_class_def(self, o: ClassDef) -> None:
            results.add(o.name)

    node.accept(ClassTraverser())
    return results
开发者ID:alexandrul,项目名称:mypy,代码行数:9,代码来源:stubgen.py


示例10: get_python_out_path

 def get_python_out_path(self, f: MypyFile) -> str:
     if f.fullname() == '__main__':
         return os.path.join(self.output_dir, basename(f.path))
     else:
         components = f.fullname().split('.')
         if os.path.basename(f.path) == '__init__.py':
             components.append('__init__.py')
         else:
             components[-1] += '.py'
         return os.path.join(self.output_dir, *components)
开发者ID:adamhaney,项目名称:mypy,代码行数:10,代码来源:build.py


示例11: generate_html_report

def generate_html_report(tree: MypyFile, path: str, type_map: Dict[Expression, Type],
                         output_dir: str) -> None:
    if is_special_module(path):
        return
    # There may be more than one right answer for "what should we do here?"
    # but this is a reasonable one.
    path = os.path.relpath(path)
    if path.startswith('..'):
        return
    visitor = StatisticsVisitor(inferred=True, typemap=type_map, all_nodes=True)
    tree.accept(visitor)
    assert not os.path.isabs(path) and not path.startswith('..')
    # This line is *wrong* if the preceding assert fails.
    target_path = os.path.join(output_dir, 'html', path)
    # replace .py or .pyi with .html
    target_path = os.path.splitext(target_path)[0] + '.html'
    assert target_path.endswith('.html')
    ensure_dir_exists(os.path.dirname(target_path))
    output = []  # type: List[str]
    append = output.append
    append('''\
<html>
<head>
  <style>
    .red { background-color: #faa; }
    .yellow { background-color: #ffa; }
    .white { }
    .lineno { color: #999; }
  </style>
</head>
<body>
<pre>''')
    num_imprecise_lines = 0
    num_lines = 0
    with open(path) as input_file:
        for i, line in enumerate(input_file):
            lineno = i + 1
            status = visitor.line_map.get(lineno, TYPE_PRECISE)
            style_map = {TYPE_PRECISE: 'white',
                         TYPE_IMPRECISE: 'yellow',
                         TYPE_ANY: 'red'}
            style = style_map[status]
            append('<span class="lineno">%4d</span>   ' % lineno +
                   '<span class="%s">%s</span>' % (style,
                                                   cgi.escape(line)))
            if status != TYPE_PRECISE:
                num_imprecise_lines += 1
            if line.strip():
                num_lines += 1
    append('</pre>')
    append('</body></html>')
    with open(target_path, 'w') as output_file:
        output_file.writelines(output)
    target_path = target_path[len(output_dir) + 1:]
    html_files.append((path, target_path, num_lines, num_imprecise_lines))
开发者ID:alexandrul,项目名称:mypy,代码行数:55,代码来源:stats.py


示例12: on_file

    def on_file(self, tree: MypyFile, type_map: Dict[Node, Type]) -> None:
        tree_source = open(tree.path).readlines()

        coverage_visitor = LineCoverageVisitor(tree_source)
        tree.accept(coverage_visitor)

        covered_lines = []
        for line_number, (_, typed) in enumerate(coverage_visitor.lines_covered):
            if typed:
                covered_lines.append(line_number + 1)

        self.lines_covered[os.path.abspath(tree.path)] = covered_lines
开发者ID:JdeH,项目名称:Transcrypt,代码行数:12,代码来源:report.py


示例13: visit_file

 def visit_file(self, file_node: MypyFile, fnam: str, options: Options,
                patches: List[Callable[[], None]]) -> None:
     self.recurse_into_functions = True
     self.errors.set_file(fnam, file_node.fullname())
     self.options = options
     self.sem.options = options
     self.patches = patches
     self.is_typeshed_file = self.errors.is_typeshed_file(fnam)
     self.sem.cur_mod_id = file_node.fullname()
     self.sem.globals = file_node.names
     with experiments.strict_optional_set(options.strict_optional):
         self.accept(file_node)
开发者ID:greatmazinger,项目名称:mypy,代码行数:12,代码来源:semanal_pass3.py


示例14: on_file

    def on_file(self, tree: MypyFile, type_map: Dict[Node, Type]) -> None:
        physical_lines = len(open(tree.path).readlines())

        func_counter = FuncCounterVisitor()
        tree.accept(func_counter)
        unannotated_funcs, annotated_funcs = func_counter.counts
        total_funcs = annotated_funcs + unannotated_funcs

        imputed_annotated_lines = (physical_lines * annotated_funcs // total_funcs
                                   if total_funcs else physical_lines)

        self.counts[tree._fullname] = (imputed_annotated_lines, physical_lines,
                                       annotated_funcs, total_funcs)
开发者ID:alunduil,项目名称:mypy,代码行数:13,代码来源:report.py


示例15: visit_mypy_file

 def visit_mypy_file(self, mfile: MypyFile) -> int:
     if mfile.fullname() in ('typing', 'abc'):
         # These module are special; their contents are currently all
         # built-in primitives.
         return -1
     
     self.enter()
     
     # Initialize non-int global variables.
     for name in sorted(mfile.names):
         node = mfile.names[name].node
         if (isinstance(node, Var) and
                 name not in nodes.implicit_module_attrs):
             v = cast(Var, node)
             if (not is_named_instance(v.type, 'builtins.int')
                     and v.fullname() != 'typing.Undefined'):
                 tmp = self.alloc_register()
                 self.add(SetRNone(tmp))
                 self.add(SetGR(v.fullname(), tmp))
     
     for d in mfile.defs:
         d.accept(self)
     self.add_implicit_return()
     self.generated['__init'] = FuncIcode(0, self.blocks,
                                          self.register_types)
     # TODO leave?
     return -1
开发者ID:FlorianLudwig,项目名称:mypy,代码行数:27,代码来源:icode.py


示例16: get_all_leaf_targets

def get_all_leaf_targets(file: MypyFile) -> List[TargetInfo]:
    """Return all leaf targets in a symbol table (module-level and methods)."""
    result = []  # type: List[TargetInfo]
    for fullname, node, active_type in file.local_definitions():
        if isinstance(node.node, (FuncDef, OverloadedFuncDef, Decorator)):
            result.append((fullname, node.node, active_type))
    return result
开发者ID:Michael0x2a,项目名称:mypy,代码行数:7,代码来源:semanal_main.py


示例17: visit_file

 def visit_file(self, file_node: MypyFile, fnam: str, options: Options,
                patches: List[Tuple[int, Callable[[], None]]]) -> None:
     self.recurse_into_functions = True
     self.errors.set_file(fnam, file_node.fullname(), scope=self.scope)
     self.options = options
     self.sem.options = options
     self.patches = patches
     self.is_typeshed_file = self.errors.is_typeshed_file(fnam)
     self.sem.cur_mod_id = file_node.fullname()
     self.cur_mod_node = file_node
     self.sem.globals = file_node.names
     with experiments.strict_optional_set(options.strict_optional):
         self.scope.enter_file(file_node.fullname())
         self.accept(file_node)
         self.analyze_symbol_table(file_node.names)
         self.scope.leave()
     del self.cur_mod_node
     self.patches = []
开发者ID:sixolet,项目名称:mypy,代码行数:18,代码来源:semanal_pass3.py


示例18: create_indirect_imported_name

def create_indirect_imported_name(file_node: MypyFile,
                                  module: str,
                                  relative: int,
                                  imported_name: str) -> Optional[SymbolTableNode]:
    """Create symbol table entry for a name imported from another module.

    These entries act as indirect references.
    """
    target_module, ok = correct_relative_import(
        file_node.fullname(),
        relative,
        module,
        file_node.is_package_init_file())
    if not ok:
        return None
    target_name = '%s.%s' % (target_module, imported_name)
    link = ImportedName(target_name)
    # Use GDEF since this refers to a module-level definition.
    return SymbolTableNode(GDEF, link)
开发者ID:python,项目名称:mypy,代码行数:19,代码来源:semanal_shared.py


示例19: visit_file

 def visit_file(self, file_node: MypyFile, fnam: str, options: Options,
                patches: List[Tuple[int, Callable[[], None]]]) -> None:
     self.recurse_into_functions = True
     self.options = options
     self.sem.options = options
     self.patches = patches
     self.is_typeshed_file = self.errors.is_typeshed_file(fnam)
     self.sem.cur_mod_id = file_node.fullname()
     self.cur_mod_node = file_node
     self.sem.globals = file_node.names
开发者ID:mananpal1997,项目名称:mypy,代码行数:10,代码来源:semanal_pass3.py


示例20: visit_mypy_file

 def visit_mypy_file(self, o: MypyFile) -> None:
     """Transform an file."""
     res = []  # type: List[Node]
     for d in o.defs:
         if isinstance(d, ClassDef):
             self._type_context = d.info
             res.extend(self.type_tf.transform_class_def(d))
             self._type_context = None
         else:
             d.accept(self)
             res.append(d)
     o.defs = res
开发者ID:akaihola,项目名称:mypy,代码行数:12,代码来源:transform.py



注:本文中的mypy.nodes.MypyFile类示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python nodes.Node类代码示例发布时间:2022-05-27
下一篇:
Python nodes.FuncDef类代码示例发布时间:2022-05-27
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap