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

Python symtable.symtable函数代码示例

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

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



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

示例1: checkfilename

 def checkfilename(brokencode):
     try:
         symtable.symtable(brokencode, "spam", "exec")
     except SyntaxError as e:
         self.assertEqual(e.filename, "spam")
     else:
         self.fail("no SyntaxError for %r" % (brokencode,))
开发者ID:BillyboyD,项目名称:main,代码行数:7,代码来源:test_symtable.py


示例2: test_annotated

 def test_annotated(self):
     st1 = symtable.symtable('def f():\n    x: int\n', 'test', 'exec')
     st2 = st1.get_children()[0]
     self.assertTrue(st2.lookup('x').is_local())
     self.assertTrue(st2.lookup('x').is_annotated())
     self.assertFalse(st2.lookup('x').is_global())
     st3 = symtable.symtable('def f():\n    x = 1\n', 'test', 'exec')
     st4 = st3.get_children()[0]
     self.assertTrue(st4.lookup('x').is_local())
     self.assertFalse(st4.lookup('x').is_annotated())
开发者ID:1st1,项目名称:cpython,代码行数:10,代码来源:test_symtable.py


示例3: __tests

def __tests():
    import symtable

    class ClassFinder(ast.NodeVisitor):
        def __init__(self, name):
            ast.NodeVisitor.__init__(self)
            self.name = name
            self.classes = []

        def visit_ClassDef(self, node):
            if node.name == self.name:
                self.classes.append(node)

    with open('tests/game2.py') as source_file:
        code = source_file.read()
        ast_node = ast.parse(code)
        symbol_table = symtable.symtable(code, 'game2.py', 'exec')
        class_finder = ClassFinder('Game')
        class_finder.visit(ast_node)
        subclass = class_finder.classes[0]
        subclass_symbol_table = symbol_table.lookup('Game').get_namespace()
        superclasses, subclass = SuperClassExtractor.extract_into_ideal_cohesion(subclass, subclass_symbol_table)
        for superclass_node in superclasses:
            print to_source(superclass_node)
            # print
            # print ast.dump(superclass_node)
            print
            print '#' * 200
            print
        print to_source(subclass)
开发者ID:wolmir,项目名称:cristina,代码行数:30,代码来源:codebase_recycling.py


示例4: __init__

 def __init__(self, code, ns=None):
     global __default_namespace__
     if ns is None:
         ns = __default_namespace__
     var = [v for v in symtable.symtable(code, '<string>', 'exec').get_identifiers() if v in ns]
     super(PythonCode, self).__init__(var=var, namespace=ns)
     self.code = compile(code, '<string>', 'exec')
开发者ID:Abramovuch,项目名称:sagecell,代码行数:7,代码来源:interact_namespace.py


示例5: parse_module

def parse_module(module_name):
    filename = module_name + ".py"
    with open(os.path.join(SOLUTIONS_DIR, filename), 'r') as f:
        source = f.read()

    srclines = source.splitlines()
    module = ast.parse(source, filename)
    table = symtable.symtable(source, filename, "exec")
    stmts = list(get_stmts(module))
    last_fun = stmts[0][0]
    lines = {name:"\n".join(srclines[s:e]).strip() for (name,(s,e)) in stmts}
    imports = dict(get_imports(module))

    def parse_dependencies(name):
        import builtins
        for tab in get_child_tables(table.lookup(name).get_namespace()):
            for g in tab.get_globals():
                if g in dir(builtins):
                    continue

                if table.lookup(g).is_imported():
                    imported = imports[g]
                    if imported[0] != "leetcode":
                        yield imported
                else:
                    yield (module_name, g)

    return last_fun, lines, {name:tuple(parse_dependencies(name)) for name in lines}
开发者ID:bhuztez,项目名称:leetcode-solution,代码行数:28,代码来源:c.py


示例6: _inspect

 def _inspect(self,string):
   symtab = symtable.symtable(string,'rule',self.mode)
   symbols = symtab.get_symbols()
   defs = [sym.get_name() for sym in symbols if sym.is_assigned()]
   refs = [sym.get_name() for sym in symbols if sym.is_referenced()]
   self.all_symbols = frozenset(symtab.get_identifiers())
   self.sym_assigned = defset = frozenset(defs)
   self.sym_internal = frozenset(defset.intersection(refs))
开发者ID:Huskyeder,项目名称:augustus,代码行数:8,代码来源:rules.py


示例7: __find_class_symbol_tables

 def __find_class_symbol_tables(self):
     class_names = self.__get_class_names()
     source_code = self.get_source_code()
     module_symbol_table = symtable.symtable(source_code, self.file_path, 'exec')
     symbol_tables = []
     for name in class_names:
         class_symbol_table = module_symbol_table.lookup(name).get_namespace()
         symbol_tables.append(class_symbol_table)
     return symbol_tables
开发者ID:wolmir,项目名称:cristina,代码行数:9,代码来源:codebase_recycling.py


示例8: get_symtable

def get_symtable(path):
	import symtable
	try:
		st = symtables[path]
	except KeyError:
		with open(path, 'r') as f:
			st = symtable.symtable(f.read(), path, 'exec')
		symtables[path] = st
	return st
开发者ID:raylu,项目名称:pigwig,代码行数:9,代码来源:conf.py


示例9: __init__

 def __init__(self, source_no_encoding, pubapi):
     # Our public API (__all__)
     self.pubapi = pubapi
     # Names of imported modules
     self.modnames = []
     self.symtab = symtable.symtable(source_no_encoding, "-", "exec")
     cst = parser.suite(source_no_encoding)
     elements = parser.ast2tuple(cst, line_info=1)
     self.names = {}
     self.walk(elements, [self.symtab])
开发者ID:Sevenops,项目名称:Simple-Scripts,代码行数:10,代码来源:o.py


示例10: __init__

 def __init__(self, source, path='<string>'):
     self.source = source
     self.path = path
     self.ast = ast.parse(source, path)
     self.symtable = symtable.symtable(source, path, 'exec')
     self.tokens = tokenize_string(source)
     cw = ChainWalker(self.ast, self.symtable)
     self.nodes = cw.nodes
     TokenAssociator(self.nodes, self.tokens)
     self.ast_map = {node.ast_node: node for node in self.nodes}
开发者ID:kentfrazier,项目名称:parsnip,代码行数:10,代码来源:__init__.py


示例11: format_table

def format_table(code_string):
    s_table = symtable(code_string, "string", "exec")
    table = []
    for child in s_table.get_children():
        row = {
            "name": child.get_name(),
            "scope": "global",
            "children": [subchild.get_name() for subchild in child.get_children()],
        }
        table.append(row)
    return s_table, table
开发者ID:DivyaShanmugam,项目名称:MoAL,代码行数:11,代码来源:symbol_table.py


示例12: getDefinitions

 def getDefinitions(self, doc, identifier):
     if doc.get_language().get_name() != "Python":
         return
     doc_location = doc.get_location()
     with open(doc_location.get_path()) as f:
         table = symtable.symtable(
             f.read(),
             doc_location.get_basename(),
             "exec",
         )
         for line in self.generateDefLines(table, identifier):
             yield doc_location, line, "", doc_location.get_path()
开发者ID:jmanoel7,项目名称:my_dot_files,代码行数:12,代码来源:PythonSymtableNavigator.py


示例13: load_file

    def load_file(filename):
        filename = os.path.abspath(filename)
        with open(filename) as fp:
            syminfo = symtable.symtable(fp.read() + '\n', filename, 'exec')

        if(os.path.splitext(filename)[1] == '.py'):
            try:
                py_compile.compile(filename, filename+'c', doraise=True)
            except py_compile.PyCompileError, msg:
                print str(msg)
                print 'Couldn\'t compile %s, stopping.' % filename
                os._exit(0)
            filename += 'c'
开发者ID:sataloger,项目名称:python-static-analysis,代码行数:13,代码来源:cfg_creator.py


示例14: test_annotated

    def test_annotated(self):
        st1 = symtable.symtable('def f():\n    x: int\n', 'test', 'exec')
        st2 = st1.get_children()[0]
        self.assertTrue(st2.lookup('x').is_local())
        self.assertTrue(st2.lookup('x').is_annotated())
        self.assertFalse(st2.lookup('x').is_global())
        st3 = symtable.symtable('def f():\n    x = 1\n', 'test', 'exec')
        st4 = st3.get_children()[0]
        self.assertTrue(st4.lookup('x').is_local())
        self.assertFalse(st4.lookup('x').is_annotated())

        # Test that annotations in the global scope are valid after the
        # variable is declared as nonlocal.
        st5 = symtable.symtable('global x\nx: int', 'test', 'exec')
        self.assertTrue(st5.lookup("x").is_global())

        # Test that annotations for nonlocals are valid after the
        # variable is declared as nonlocal.
        st6 = symtable.symtable('def g():\n'
                                '    x = 2\n'
                                '    def f():\n'
                                '        nonlocal x\n'
                                '    x: int',
                                'test', 'exec')
开发者ID:Eyepea,项目名称:cpython,代码行数:24,代码来源:test_symtable.py


示例15: test_filename_correct

 def test_filename_correct(self):
     ### Bug tickler: SyntaxError file name correct whether error raised
     ### while parsing or building symbol table.
     def checkfilename(brokencode):
         try:
             symtable.symtable(brokencode, "spam", "exec")
         except SyntaxError as e:
             self.assertEqual(e.filename, "spam")
         else:
             self.fail("no SyntaxError for %r" % (brokencode,))
     checkfilename("def f(x): foo)(")  # parse-time
     checkfilename("def f(x): global x")  # symtable-build-time
     symtable.symtable("pass", b"spam", "exec")
     with self.assertRaises(TypeError):
         symtable.symtable("pass", bytearray(b"spam"), "exec")
     symtable.symtable("pass", memoryview(b"spam"), "exec")
     with self.assertRaises(TypeError):
         symtable.symtable("pass", list(b"spam"), "exec")
开发者ID:CabbageHead-360,项目名称:cpython,代码行数:18,代码来源:test_symtable.py


示例16: symtabdump

def symtabdump(fn):
    if not os.path.exists(fn):
        print "%s doesn't exist" % fn
        raise SystemExit()
    text = open(fn).read()
    mod = symtable.symtable(text, os.path.split(fn)[1], "exec")
    def getidents(obj, indent=""):
        ret = ""
        ret += """%sSym_type: %s
%sSym_name: %s
%sSym_lineno: %s
%sSym_nested: %s
%sSym_haschildren: %s
""" % (
        indent, obj.get_type(),
        indent, obj.get_name(),
        indent, obj.get_lineno(),
        indent, obj.is_nested(),
        indent, obj.has_children())
        if obj.get_type() == "function":
            ret += "%sFunc_params: %s\n%sFunc_locals: %s\n%sFunc_globals: %s\n%sFunc_frees: %s\n" % (
                    indent, sorted(obj.get_parameters()),
                    indent, sorted(obj.get_locals()),
                    indent, sorted(obj.get_globals()),
                    indent, sorted(obj.get_frees()))
        elif obj.get_type() == "class":
            ret += "%sClass_methods: %s\n" % (
                    indent, sorted(obj.get_methods()))
        ret += "%s-- Identifiers --\n" % indent
        for ident in sorted(obj.get_identifiers()):
            info = obj.lookup(ident)
            ret += "%sname: %s\n  %sis_referenced: %s\n  %sis_imported: %s\n  %sis_parameter: %s\n  %sis_global: %s\n  %sis_declared_global: %s\n  %sis_local: %s\n  %sis_free: %s\n  %sis_assigned: %s\n  %sis_namespace: %s\n  %snamespaces: [\n%s  %s]\n" % (
                    indent, info.get_name(),
                    indent, info.is_referenced(),
                    indent, info.is_imported(),
                    indent, info.is_parameter(),
                    indent, info.is_global(),
                    indent, info.is_declared_global(),
                    indent, info.is_local(),
                    indent, info.is_free(),
                    indent, info.is_assigned(),
                    indent, info.is_namespace(),
                    indent, '\n'.join([getidents(x, indent + "    ") for x in info.get_namespaces()]),
                    indent
                    )
        return ret
    return getidents(mod)
开发者ID:anasm87,项目名称:skulpt,代码行数:47,代码来源:skulpt.py


示例17: to_one_line

def to_one_line(original):
    # original :: string
    # :: string
    t = ast.parse(original)
    table = symtable.symtable(original, '<string>', 'exec')

    original = original.strip()

    # If there's only one line anyways, be lazy
    if len(original.splitlines()) == 1 and \
       len(t.body) == 1 and \
       type(t.body[0]) in (ast.Delete, ast.Assign, ast.AugAssign, ast.Print,
                           ast.Raise, ast.Assert, ast.Import, ast.ImportFrom,
                           ast.Exec, ast.Global, ast.Expr, ast.Pass):
        return original

    return get_init_code(t, table)
开发者ID:paris-ci,项目名称:onelinerizer,代码行数:17,代码来源:main.py


示例18: __init__

 def __init__(self, name="", path=None, file_name="<unknown>", code=None):
     CKClass.__init__(self, name, None, None, None)
     self.path = path
     self.descriptor = pyclbr.readmodule_ex(self.name, path)
     self.file_name = file_name
     self.code = code
     if self.code:
         self.symbol_table = symtable.symtable(self.code, self.file_name, 'exec')
         self.ast_node = ast.parse(self.code, self.file_name)
     self.classes = {}
     class_node_finder = ClassNodeFinder(self.ast_node)
     for class_name in self.descriptor.keys():
         class_descriptor = self.descriptor[class_name]
         if isinstance(class_descriptor, pyclbr.Class):
             if class_descriptor.module == self.name:
                 class_table = self.symbol_table.lookup(class_name).get_namespace()
                 class_node = class_node_finder.find(class_name)
                 ck_class = CKClass(class_name, class_descriptor, class_table, class_node)
                 ck_class.extract_references()
                 self.classes[self.name + "." + class_name] = ck_class
开发者ID:wolmir,项目名称:cristina,代码行数:20,代码来源:pyck.py


示例19: parse_code

def parse_code(source_code, filename='app.py'):
    # type: (str, str) -> ParsedCode
    parsed = ast.parse(source_code, filename)
    table = symtable.symtable(source_code, filename, 'exec')
    return ParsedCode(parsed, ChainedSymbolTable(table, table))
开发者ID:awslabs,项目名称:chalice,代码行数:5,代码来源:analyzer.py


示例20: get_names

if __name__ == "__main__":
    import sys
    from compiler import parseFile, walk
    import symtable

    def get_names(syms):
        return [s for s in [s.get_name() for s in syms.get_symbols()]
                if not (s.startswith('_[') or s.startswith('.'))]

    for file in sys.argv[1:]:
        print file
        f = open(file)
        buf = f.read()
        f.close()
        syms = symtable.symtable(buf, file, "exec")
        mod_names = get_names(syms)
        tree = parseFile(file)
        s = SymbolVisitor()
        walk(tree, s)

        # compare module-level symbols
        names2 = s.scopes[tree].get_names()

        if not list_eq(mod_names, names2):
            print
            print "oops", file
            print sorted(mod_names)
            print sorted(names2)
            sys.exit(-1)
开发者ID:0xcc,项目名称:pyston,代码行数:29,代码来源:symbols.py



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


鲜花

握手

雷人

路过

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

请发表评论

全部评论

专题导读
上一篇:
Python homeserver.HomeServerConfig类代码示例发布时间:2022-05-27
下一篇:
Python functions.express函数代码示例发布时间: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