当前位置: 首页>>代码示例>>Python>>正文


Python _ast.If方法代码示例

本文整理汇总了Python中_ast.If方法的典型用法代码示例。如果您正苦于以下问题:Python _ast.If方法的具体用法?Python _ast.If怎么用?Python _ast.If使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在_ast的用法示例。


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

示例1: visit_If

# 需要导入模块: import _ast [as 别名]
# 或者: from _ast import If [as 别名]
def visit_If(self, node):
        self.newline()
        self.write("if ")
        self.visit(node.test)
        self.write(":")
        self.body(node.body)
        while True:
            else_ = node.orelse
            if len(else_) == 1 and isinstance(else_[0], If):
                node = else_[0]
                self.newline()
                self.write("elif ")
                self.visit(node.test)
                self.write(":")
                self.body(node.body)
            else:
                self.newline()
                self.write("else:")
                self.body(else_)
                break 
开发者ID:remg427,项目名称:misp42splunk,代码行数:22,代码来源:_ast_util.py

示例2: test_compile_ast

# 需要导入模块: import _ast [as 别名]
# 或者: from _ast import If [as 别名]
def test_compile_ast(self):
        fname = __file__
        if fname.lower().endswith(('pyc', 'pyo')):
            fname = fname[:-1]
        with open(fname, 'r') as f:
            fcontents = f.read()
        sample_code = [
            ['<assign>', 'x = 5'],
            ['<print1>', 'print 1'],
            ['<printv>', 'print v'],
            ['<printTrue>', 'print True'],
            ['<printList>', 'print []'],
            ['<ifblock>', """if True:\n    pass\n"""],
            ['<forblock>', """for n in [1, 2, 3]:\n    print n\n"""],
            ['<deffunc>', """def foo():\n    pass\nfoo()\n"""],
            [fname, fcontents],
        ]

        for fname, code in sample_code:
            co1 = compile(code, '%s1' % fname, 'exec')
            ast = compile(code, '%s2' % fname, 'exec', _ast.PyCF_ONLY_AST)
            self.assertTrue(type(ast) == _ast.Module)
            co2 = compile(ast, '%s3' % fname, 'exec')
            self.assertEqual(co1, co2)
            # the code object's filename comes from the second compilation step
            self.assertEqual(co2.co_filename, '%s3' % fname)

        # raise exception when node type doesn't match with compile mode
        co1 = compile('print 1', '<string>', 'exec', _ast.PyCF_ONLY_AST)
        self.assertRaises(TypeError, compile, co1, '<ast>', 'eval')

        # raise exception when node type is no start node
        self.assertRaises(TypeError, compile, _ast.If(), '<ast>', 'exec')

        # raise exception when node has invalid children
        ast = _ast.Module()
        ast.body = [_ast.BoolOp()]
        self.assertRaises(TypeError, compile, ast, '<ast>', 'exec') 
开发者ID:IronLanguages,项目名称:ironpython2,代码行数:40,代码来源:test_compile.py

示例3: visit_if

# 需要导入模块: import _ast [as 别名]
# 或者: from _ast import If [as 别名]
def visit_if(self, node: _ast.If):  # test, body, orelse
        stmts = node.body if self._run(node.test) else node.orelse
        for stmt in stmts:
            self._run(stmt)
        return 
开发者ID:item4,项目名称:yui,代码行数:7,代码来源:calc.py

示例4: test_compile_ast

# 需要导入模块: import _ast [as 别名]
# 或者: from _ast import If [as 别名]
def test_compile_ast(self):
        fname = __file__
        if fname.lower().endswith('pyc'):
            fname = fname[:-1]
        with open(fname, 'r') as f:
            fcontents = f.read()
        sample_code = [
            ['<assign>', 'x = 5'],
            ['<ifblock>', """if True:\n    pass\n"""],
            ['<forblock>', """for n in [1, 2, 3]:\n    print(n)\n"""],
            ['<deffunc>', """def foo():\n    pass\nfoo()\n"""],
            [fname, fcontents],
        ]

        for fname, code in sample_code:
            co1 = compile(code, '%s1' % fname, 'exec')
            ast = compile(code, '%s2' % fname, 'exec', _ast.PyCF_ONLY_AST)
            self.assertTrue(type(ast) == _ast.Module)
            co2 = compile(ast, '%s3' % fname, 'exec')
            self.assertEqual(co1, co2)
            # the code object's filename comes from the second compilation step
            self.assertEqual(co2.co_filename, '%s3' % fname)

        # raise exception when node type doesn't match with compile mode
        co1 = compile('print(1)', '<string>', 'exec', _ast.PyCF_ONLY_AST)
        self.assertRaises(TypeError, compile, co1, '<ast>', 'eval')

        # raise exception when node type is no start node
        self.assertRaises(TypeError, compile, _ast.If(), '<ast>', 'exec')

        # raise exception when node has invalid children
        ast = _ast.Module()
        ast.body = [_ast.BoolOp()]
        self.assertRaises(TypeError, compile, ast, '<ast>', 'exec') 
开发者ID:Microvellum,项目名称:Fluid-Designer,代码行数:36,代码来源:test_compile.py

示例5: test_compile_ast

# 需要导入模块: import _ast [as 别名]
# 或者: from _ast import If [as 别名]
def test_compile_ast(self):
        fname = __file__
        if fname.lower().endswith(('pyc', 'pyo')):
            fname = fname[:-1]
        with open(fname, 'r') as f:
            fcontents = f.read()
        sample_code = [
            ['<assign>', 'x = 5'],
            ['<ifblock>', """if True:\n    pass\n"""],
            ['<forblock>', """for n in [1, 2, 3]:\n    print(n)\n"""],
            ['<deffunc>', """def foo():\n    pass\nfoo()\n"""],
            [fname, fcontents],
        ]

        for fname, code in sample_code:
            co1 = compile(code, '%s1' % fname, 'exec')
            ast = compile(code, '%s2' % fname, 'exec', _ast.PyCF_ONLY_AST)
            self.assertTrue(type(ast) == _ast.Module)
            co2 = compile(ast, '%s3' % fname, 'exec')
            self.assertEqual(co1, co2)
            # the code object's filename comes from the second compilation step
            self.assertEqual(co2.co_filename, '%s3' % fname)

        # raise exception when node type doesn't match with compile mode
        co1 = compile('print(1)', '<string>', 'exec', _ast.PyCF_ONLY_AST)
        self.assertRaises(TypeError, compile, co1, '<ast>', 'eval')

        # raise exception when node type is no start node
        self.assertRaises(TypeError, compile, _ast.If(), '<ast>', 'exec')

        # raise exception when node has invalid children
        ast = _ast.Module()
        ast.body = [_ast.BoolOp()]
        self.assertRaises(TypeError, compile, ast, '<ast>', 'exec') 
开发者ID:IronLanguages,项目名称:ironpython3,代码行数:36,代码来源:test_compile.py

示例6: visit_If

# 需要导入模块: import _ast [as 别名]
# 或者: from _ast import If [as 别名]
def visit_If(self, node):
    # Write out the if block
    if not self.elseif:
      print >> self.o
      print >> self.o, self.ident*" " + "  if (",
    else:
      print >> self.o, self.ident*" " + "  else if (",
      self.elseif = False
    self.visit(node.test)
    print >> self.o, " ) {"
    # Write out the body
    for body in node.body:
      self.ident += 2
      self.visit(body)
      print >> self.o, ';'
      self.ident -= 2
    print >> self.o, self.ident*" " + "  }"
    # Write out an an elif block
    if len(node.orelse) == 1 and isinstance(node.orelse[0], _ast.If):
      self.elseif = True
      self.visit(node.orelse[0])
    # Write out an else block
    elif node.orelse:
      print >> self.o, self.ident*" " + "  else {"
      for orelse in node.orelse:
        self.ident += 2
        self.visit(orelse)
        print >> self.o, ';'
        self.ident -= 2
      print >> self.o, self.ident*" " + "  }"

  #------------------------------------------------------------------
  # visit_While
  #---------------------------------------------------------------------
  # TODO: does this work? 
开发者ID:cornell-brg,项目名称:pymtl,代码行数:37,代码来源:cpp.py

示例7: getAlternatives

# 需要导入模块: import _ast [as 别名]
# 或者: from _ast import If [as 别名]
def getAlternatives(n):
        if isinstance(n, (ast.If, ast.TryFinally)):
            return [n.body]
        if isinstance(n, ast.TryExcept):
            return [n.body + n.orelse] + [[hdl] for hdl in n.handlers] 
开发者ID:zrzka,项目名称:blackmamba,代码行数:7,代码来源:checker.py

示例8: handleNodeDelete

# 需要导入模块: import _ast [as 别名]
# 或者: from _ast import If [as 别名]
def handleNodeDelete(self, node):

        def on_conditional_branch():
            """
            Return `True` if node is part of a conditional body.
            """
            current = getattr(node, 'parent', None)
            while current:
                if isinstance(current, (ast.If, ast.While, ast.IfExp)):
                    return True
                current = getattr(current, 'parent', None)
            return False

        name = getNodeName(node)
        if not name:
            return

        if on_conditional_branch():
            # We cannot predict if this conditional branch is going to
            # be executed.
            return

        if isinstance(self.scope, FunctionScope) and name in self.scope.globals:
            self.scope.globals.remove(name)
        else:
            try:
                del self.scope[name]
            except KeyError:
                self.report(messages.UndefinedName, node, name) 
开发者ID:zrzka,项目名称:blackmamba,代码行数:31,代码来源:checker.py

示例9: DICT

# 需要导入模块: import _ast [as 别名]
# 或者: from _ast import If [as 别名]
def DICT(self, node):
        # Complain if there are duplicate keys with different values
        # If they have the same value it's not going to cause potentially
        # unexpected behaviour so we'll not complain.
        keys = [
            convert_to_value(key) for key in node.keys
        ]

        key_counts = counter(keys)
        duplicate_keys = [
            key for key, count in key_counts.items()
            if count > 1
        ]

        for key in duplicate_keys:
            key_indices = [i for i, i_key in enumerate(keys) if i_key == key]

            values = counter(
                convert_to_value(node.values[index])
                for index in key_indices
            )
            if any(count == 1 for value, count in values.items()):
                for key_index in key_indices:
                    key_node = node.keys[key_index]
                    if isinstance(key, VariableKey):
                        self.report(messages.MultiValueRepeatedKeyVariable,
                                    key_node,
                                    key.name)
                    else:
                        self.report(
                            messages.MultiValueRepeatedKeyLiteral,
                            key_node,
                            key,
                        )
        self.handleChildren(node) 
开发者ID:zrzka,项目名称:blackmamba,代码行数:37,代码来源:checker.py

示例10: ANNASSIGN

# 需要导入模块: import _ast [as 别名]
# 或者: from _ast import If [as 别名]
def ANNASSIGN(self, node):
        if node.value:
            # Only bind the *targets* if the assignment has a value.
            # Otherwise it's not really ast.Store and shouldn't silence
            # UndefinedLocal warnings.
            self.handleNode(node.target, node)
        self.handleNode(node.annotation, node)
        if node.value:
            # If the assignment has value, handle the *value* now.
            self.handleNode(node.value, node) 
开发者ID:zrzka,项目名称:blackmamba,代码行数:12,代码来源:checker.py

示例11: handleNodeDelete

# 需要导入模块: import _ast [as 别名]
# 或者: from _ast import If [as 别名]
def handleNodeDelete(self, node):

        def on_conditional_branch():
            """
            Return `True` if node is part of a conditional body.
            """
            current = getattr(node, 'parent', None)
            while current:
                if isinstance(current, (ast.If, ast.While, ast.IfExp)):
                    return True
                current = getattr(current, 'parent', None)
            return False

        name = getNodeName(node)
        if not name:
            return

        if on_conditional_branch():
            # We can not predict if this conditional branch is going to
            # be executed.
            return

        if isinstance(self.scope, FunctionScope) and name in self.scope.globals:
            self.scope.globals.remove(name)
        else:
            try:
                del self.scope[name]
            except KeyError:
                self.report(messages.UndefinedName, node, name) 
开发者ID:QQuick,项目名称:Transcrypt,代码行数:31,代码来源:checker.py

示例12: test_compile_ast

# 需要导入模块: import _ast [as 别名]
# 或者: from _ast import If [as 别名]
def test_compile_ast(self):
        fname = __file__
        if fname.lower().endswith(('pyc', 'pyo')):
            fname = fname[:-1]
        with open(fname, 'r') as f:
            fcontents = f.read()
        sample_code = [
            ['<assign>', 'x = 5'],
            ['<print1>', 'print 1'],
            ['<printv>', 'print v'],
            ['<printTrue>', 'print True'],
            ['<printList>', 'print []'],
            ['<ifblock>', """if True:\n    pass\n"""],
            ['<forblock>', """for n in [1, 2, 3]:\n    print n\n"""],
            ['<deffunc>', """def foo():\n    pass\nfoo()\n"""],
            #FIXME: Next one not working in Jython:
            #[fname, fcontents],
        ]

        for fname, code in sample_code:
            co1 = compile(code, '%s1' % fname, 'exec')
            ast = compile(code, '%s2' % fname, 'exec', _ast.PyCF_ONLY_AST)
            self.assert_(type(ast) == _ast.Module)
            co2 = compile(ast, '%s3' % fname, 'exec')
            if not test_support.is_jython:
                self.assertEqual(co1, co2)
            # the code object's filename comes from the second compilation step
            self.assertEqual(co2.co_filename, '%s3' % fname)

        # raise exception when node type doesn't match with compile mode
        co1 = compile('print 1', '<string>', 'exec', _ast.PyCF_ONLY_AST)
        #FIXME: raises wrong error in Jython.
        #self.assertRaises(TypeError, compile, co1, '<ast>', 'eval')

        # raise exception when node type is no start node
        self.assertRaises(TypeError, compile, _ast.If(), '<ast>', 'exec')

        # raise exception when node has invalid children
        ast = _ast.Module()
        ast.body = [_ast.BoolOp()]
        #FIXME: raises NPE in Jython.
        #self.assertRaises(TypeError, compile, ast, '<ast>', 'exec') 
开发者ID:Acmesec,项目名称:CTFCrackTools-V2,代码行数:44,代码来源:test_compile.py


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