Python _ast 模块,Tuple() 实例源码

我们从Python开源项目中,提取了以下41个代码示例,用于说明如何使用_ast.Tuple()

项目:lambdazen    作者:brthor    | 项目源码 | 文件源码
def visit_Compare(self, node):
        """
        :type node: _ast.FunctionDef
        """

        is_lambda_def = len(node.ops) == 1\
                        and type(node.ops[0]) is _ast.Gt \
                        and (type(node.left) is _ast.Tuple or type(node.left) is _ast.Name) \
                        and all(map(lambda t: type(t) == _ast.Name, getattr(node.left, 'elts', [])))

        if not is_lambda_def:
            return node

        arguments = _transform_function_arguments(node.left)
        function_body = node.comparators[0]

        lambda_ast_transform = ast.Lambda(args=arguments,
                                          body=function_body,
                                          lineno=node.lineno,
                                          col_offset=node.col_offset)
        return lambda_ast_transform
项目:ooda    作者:gisce    | 项目源码 | 文件源码
def _convert(node):
        if isinstance(node, ast.Str):
            return node.s
        elif isinstance(node, ast.Num):
            return node.n
        elif isinstance(node, ast.Tuple):
            return tuple(map(_convert, node.elts))
        elif isinstance(node, ast.List):
            return list(map(_convert, node.elts))
        elif isinstance(node, ast.Dict):
            return dict((_convert(k), _convert(v)) for k, v
                        in zip(node.keys, node.values))
        elif isinstance(node, ast.Name):
            if node.id in SAFE_CONSTANTS:
                return SAFE_CONSTANTS[node.id]
        raise ValueError('malformed or disallowed expression')
项目:sublimeTextConfig    作者:luoye-fe    | 项目源码 | 文件源码
def convert_to_value(item):
    if isinstance(item, ast.Str):
        return item.s
    elif hasattr(ast, 'Bytes') and isinstance(item, ast.Bytes):
        return item.s
    elif isinstance(item, ast.Tuple):
        return tuple(convert_to_value(i) for i in item.elts)
    elif isinstance(item, ast.Num):
        return item.n
    elif isinstance(item, ast.Name):
        result = VariableKey(item=item)
        constants_lookup = {
            'True': True,
            'False': False,
            'None': None,
        }
        return constants_lookup.get(
            result.name,
            result,
        )
    elif (not PY33) and isinstance(item, ast.NameConstant):
        # None, True, False are nameconstants in python3, but names in 2
        return item.value
    else:
        return UnhandledKeyType()
项目:sublimeTextConfig    作者:luoye-fe    | 项目源码 | 文件源码
def TRY(self, node):
        handler_names = []
        # List the exception handlers
        for i, handler in enumerate(node.handlers):
            if isinstance(handler.type, ast.Tuple):
                for exc_type in handler.type.elts:
                    handler_names.append(getNodeName(exc_type))
            elif handler.type:
                handler_names.append(getNodeName(handler.type))

            if handler.type is None and i < len(node.handlers) - 1:
                self.report(messages.DefaultExceptNotLast, handler)
        # Memorize the except handlers and process the body
        self.exceptHandlers.append(handler_names)
        for child in node.body:
            self.handleNode(child, node)
        self.exceptHandlers.pop()
        # Process the other nodes: "except:", "else:", "finally:"
        self.handleChildren(node, omit='body')
项目:blackmamba    作者:zrzka    | 项目源码 | 文件源码
def convert_to_value(item):
    if isinstance(item, ast.Str):
        return item.s
    elif hasattr(ast, 'Bytes') and isinstance(item, ast.Bytes):
        return item.s
    elif isinstance(item, ast.Tuple):
        return tuple(convert_to_value(i) for i in item.elts)
    elif isinstance(item, ast.Num):
        return item.n
    elif isinstance(item, ast.Name):
        result = VariableKey(item=item)
        constants_lookup = {
            'True': True,
            'False': False,
            'None': None,
        }
        return constants_lookup.get(
            result.name,
            result,
        )
    elif (not PY33) and isinstance(item, ast.NameConstant):
        # None, True, False are nameconstants in python3, but names in 2
        return item.value
    else:
        return UnhandledKeyType()
项目:blackmamba    作者:zrzka    | 项目源码 | 文件源码
def TRY(self, node):
        handler_names = []
        # List the exception handlers
        for i, handler in enumerate(node.handlers):
            if isinstance(handler.type, ast.Tuple):
                for exc_type in handler.type.elts:
                    handler_names.append(getNodeName(exc_type))
            elif handler.type:
                handler_names.append(getNodeName(handler.type))

            if handler.type is None and i < len(node.handlers) - 1:
                self.report(messages.DefaultExceptNotLast, handler)
        # Memorize the except handlers and process the body
        self.exceptHandlers.append(handler_names)
        for child in node.body:
            self.handleNode(child, node)
        self.exceptHandlers.pop()
        # Process the other nodes: "except:", "else:", "finally:"
        self.handleChildren(node, omit='body')
项目:femtocode    作者:diana-hep    | 项目源码 | 文件源码
def make_const(arg, lineno=0, col_offset=0):
    kw = {'lineno':lineno, 'col_offset':col_offset}

    if isinstance(arg, str):
        const = _ast.Str(s=arg, **kw)
    elif isinstance(arg, (int, float, complex)):
        const = _ast.Num(n=arg, **kw)
    elif arg is None:
        const = _ast.Name(id='None', ctx=_ast.Load(), **kw)
    elif isinstance(arg, tuple):
        elts = []
        for item in arg:
            elts.append(make_const(item, **kw))
        const = _ast.Tuple(elts=elts, ctx=_ast.Load(), **kw)
    else:
        const = arg

    return const
项目:femtocode    作者:diana-hep    | 项目源码 | 文件源码
def UNPACK_SEQUENCE(self, instr):
        nargs = instr.oparg

        nodes = []
        ast_tuple = _ast.Tuple(elts=nodes, ctx=_ast.Store(), lineno=instr.lineno, col_offset=0)
        for i in range(nargs):
            nex_instr = self.ilst.pop(0)
            self.ast_stack.append(None)
            self.visit(nex_instr)

            node = self.ast_stack.pop()
            nodes.append(node.targets[0])

        expr = self.ast_stack.pop()
        if isinstance(expr, _ast.Assign):
            assgn = expr 
            assgn.targets.append(ast_tuple)

            value_dup = self.ast_stack.pop()

            assert cmp_ast(assgn.value, value_dup)

        else:
            assgn = _ast.Assign(targets=[ast_tuple], value=expr, lineno=instr.lineno, col_offset=0)
        self.ast_stack.append(assgn)
项目:wuye.vim    作者:zhaoyingnan911    | 项目源码 | 文件源码
def TRY(self, node):
        handler_names = []
        # List the exception handlers
        for handler in node.handlers:
            if isinstance(handler.type, ast.Tuple):
                for exc_type in handler.type.elts:
                    handler_names.append(getNodeName(exc_type))
            elif handler.type:
                handler_names.append(getNodeName(handler.type))
        # Memorize the except handlers and process the body
        self.exceptHandlers.append(handler_names)
        for child in node.body:
            self.handleNode(child, node)
        self.exceptHandlers.pop()
        # Process the other nodes: "except:", "else:", "finally:"
        self.handleChildren(node, omit='body')
项目:Flask_Blog    作者:sugarguo    | 项目源码 | 文件源码
def _expand_tuples(self, args):
        for arg in args:
            if isinstance(arg, _ast.Tuple):
                for n in arg.elts:
                    yield n
            else:
                yield arg
项目:lambdazen    作者:brthor    | 项目源码 | 文件源码
def _is_multiline_lambda(function_body_node):
    return type(function_body_node) is _ast.Tuple or type(function_body_node) is _ast.List
项目:flasky    作者:RoseOu    | 项目源码 | 文件源码
def _expand_tuples(self, args):
            for arg in args:
                if isinstance(arg, _ast.Tuple):
                    for n in arg.elts:
                        yield n
                else:
                    yield arg
项目:oa_qian    作者:sunqb    | 项目源码 | 文件源码
def _expand_tuples(self, args):
        for arg in args:
            if isinstance(arg, _ast.Tuple):
                for n in arg.elts:
                    yield n
            else:
                yield arg
项目:chihu    作者:yelongyu    | 项目源码 | 文件源码
def _expand_tuples(self, args):
        for arg in args:
            if isinstance(arg, _ast.Tuple):
                for n in arg.elts:
                    yield n
            else:
                yield arg
项目:ShelbySearch    作者:Agentscreech    | 项目源码 | 文件源码
def _expand_tuples(self, args):
        for arg in args:
            if isinstance(arg, _ast.Tuple):
                for n in arg.elts:
                    yield n
            else:
                yield arg
项目:pyetje    作者:rorlika    | 项目源码 | 文件源码
def _expand_tuples(self, args):
            for arg in args:
                if isinstance(arg, _ast.Tuple):
                    for n in arg.elts:
                        yield n
                else:
                    yield arg
项目:Price-Comparator    作者:Thejas-1    | 项目源码 | 文件源码
def _expand_tuples(self, args):
        for arg in args:
            if isinstance(arg, _ast.Tuple):
                for n in arg.elts:
                    yield n
            else:
                yield arg
项目:Callandtext    作者:iaora    | 项目源码 | 文件源码
def _expand_tuples(self, args):
        for arg in args:
            if isinstance(arg, _ast.Tuple):
                for n in arg.elts:
                    yield n
            else:
                yield arg
项目:splunk_ta_ps4_f1_2016    作者:jonathanvarley    | 项目源码 | 文件源码
def _expand_tuples(self, args):
        for arg in args:
            if isinstance(arg, _ast.Tuple):
                for n in arg.elts:
                    yield n
            else:
                yield arg
项目:TA-SyncKVStore    作者:georgestarcher    | 项目源码 | 文件源码
def _expand_tuples(self, args):
        for arg in args:
            if isinstance(arg, _ast.Tuple):
                for n in arg.elts:
                    yield n
            else:
                yield arg
项目:cb-defense-splunk-app    作者:carbonblack    | 项目源码 | 文件源码
def _expand_tuples(self, args):
        for arg in args:
            if isinstance(arg, _ast.Tuple):
                for n in arg.elts:
                    yield n
            else:
                yield arg
项目:sublimeTextConfig    作者:luoye-fe    | 项目源码 | 文件源码
def __init__(self, name, source, scope):
        if '__all__' in scope and isinstance(source, ast.AugAssign):
            self.names = list(scope['__all__'].names)
        else:
            self.names = []
        if isinstance(source.value, (ast.List, ast.Tuple)):
            for node in source.value.elts:
                if isinstance(node, ast.Str):
                    self.names.append(node.s)
        super(ExportBinding, self).__init__(name, source)
项目:sublimeTextConfig    作者:luoye-fe    | 项目源码 | 文件源码
def getParent(self, node):
        # Lookup the first parent which is not Tuple, List or Starred
        while True:
            node = node.parent
            if not hasattr(node, 'elts') and not hasattr(node, 'ctx'):
                return node
项目:sublimeTextConfig    作者:luoye-fe    | 项目源码 | 文件源码
def ASSERT(self, node):
        if isinstance(node.test, ast.Tuple) and node.test.elts != []:
            self.report(messages.AssertTuple, node)
        self.handleChildren(node)
项目:webapp    作者:superchilli    | 项目源码 | 文件源码
def _expand_tuples(self, args):
        for arg in args:
            if isinstance(arg, _ast.Tuple):
                for n in arg.elts:
                    yield n
            else:
                yield arg
项目:QualquerMerdaAPI    作者:tiagovizoto    | 项目源码 | 文件源码
def _expand_tuples(self, args):
        for arg in args:
            if isinstance(arg, _ast.Tuple):
                for n in arg.elts:
                    yield n
            else:
                yield arg
项目:gardenbot    作者:GoestaO    | 项目源码 | 文件源码
def _expand_tuples(self, args):
        for arg in args:
            if isinstance(arg, _ast.Tuple):
                for n in arg.elts:
                    yield n
            else:
                yield arg
项目:flask-zhenai-mongo-echarts    作者:Fretice    | 项目源码 | 文件源码
def _expand_tuples(self, args):
        for arg in args:
            if isinstance(arg, _ast.Tuple):
                for n in arg.elts:
                    yield n
            else:
                yield arg
项目:teleport    作者:eomsoft    | 项目源码 | 文件源码
def _expand_tuples(self, args):
        for arg in args:
            if isinstance(arg, _ast.Tuple):
                for n in arg.elts:
                    yield n
            else:
                yield arg
项目:blackmamba    作者:zrzka    | 项目源码 | 文件源码
def __init__(self, name, source, scope):
        if '__all__' in scope and isinstance(source, ast.AugAssign):
            self.names = list(scope['__all__'].names)
        else:
            self.names = []
        if isinstance(source.value, (ast.List, ast.Tuple)):
            for node in source.value.elts:
                if isinstance(node, ast.Str):
                    self.names.append(node.s)
        super(ExportBinding, self).__init__(name, source)
项目:blackmamba    作者:zrzka    | 项目源码 | 文件源码
def getParent(self, node):
        # Lookup the first parent which is not Tuple, List or Starred
        while True:
            node = node.parent
            if not hasattr(node, 'elts') and not hasattr(node, 'ctx'):
                return node
项目:blackmamba    作者:zrzka    | 项目源码 | 文件源码
def ASSERT(self, node):
        if isinstance(node.test, ast.Tuple) and node.test.elts != []:
            self.report(messages.AssertTuple, node)
        self.handleChildren(node)
项目:femtocode    作者:diana-hep    | 项目源码 | 文件源码
def BUILD_CLASS(self, instr):

        call_func = self.ast_stack.pop()

        assert isinstance(call_func, _ast.Call)

        func = call_func.func

        assert isinstance(func, _ast.FunctionDef)

        code = func.body
        pop_assignment(code, '__module__')
        doc = pop_doc(code)

        ret = code.pop()

        assert isinstance(ret, _ast.Return) and ret.value == 'LOAD_LOCALS'

        bases = self.ast_stack.pop()

        assert isinstance(bases, _ast.Tuple)
        bases = bases.elts
        name = self.ast_stack.pop()

        class_ = _ast.ClassDef(name=name, bases=bases, body=code, decorator_list=[],
                               lineno=instr.lineno, col_offset=0)

        self.ast_stack.append(class_)
项目:femtocode    作者:diana-hep    | 项目源码 | 文件源码
def ROT_TWO(self, instr):

        one = self.ast_stack.pop()
        two = self.ast_stack.pop()

        if self.ilst[0].opname == 'STORE_NAME':

            kw = dict(lineno=instr.lineno, col_offset=0)
            stores = []
            while self.ilst[0].opname == 'STORE_NAME':
                stores.append(self.ilst.pop(0))

            assert len(stores) <= 3, stores
            elts_load = [one, two]
            if len(stores) == 3:
                elts_load.insert(0, self.ast_stack.pop())

            tup_load = _ast.Tuple(elts=elts_load[::-1], ctx=_ast.Load(), **kw)

            elts_store = [_ast.Name(id=store.arg, ctx=_ast.Store(), **kw) for store in stores]
            tup_store = _ast.Tuple(elts=elts_store, ctx=_ast.Store(), **kw)

            assgn = _ast.Assign(value=tup_load, targets=[tup_store], **kw)
            self.ast_stack.append(assgn)
#            self.ast_stack.append(tup_store)
        else:
            self.ast_stack.append(one)
            self.ast_stack.append(two)
项目:femtocode    作者:diana-hep    | 项目源码 | 文件源码
def BUILD_TUPLE(self, instr):

        nitems = instr.oparg

        nodes = []
        list_ = _ast.Tuple(elts=nodes, ctx=_ast.Load(), lineno=instr.lineno, col_offset=0)
        for i in range(nitems):
            nodes.insert(0, self.ast_stack.pop())

        if any([item == 'CLOSURE' for item in nodes]):
            assert all([item == 'CLOSURE' for item in nodes])
            return

        self.ast_stack.append(list_)
项目:femtocode    作者:diana-hep    | 项目源码 | 文件源码
def visitIndex(self, node):
        if isinstance(node.value, _ast.Tuple):
            with self.no_indent:
                self.visit(node.value, brace=['', ''])
        else:
            self.print('{:node}', node.value)
项目:wuye.vim    作者:zhaoyingnan911    | 项目源码 | 文件源码
def __init__(self, name, source, scope):
        if '__all__' in scope and isinstance(source, ast.AugAssign):
            self.names = list(scope['__all__'].names)
        else:
            self.names = []
        if isinstance(source.value, (ast.List, ast.Tuple)):
            for node in source.value.elts:
                if isinstance(node, ast.Str):
                    self.names.append(node.s)
        super(ExportBinding, self).__init__(name, source)
项目:wuye.vim    作者:zhaoyingnan911    | 项目源码 | 文件源码
def getParent(self, node):
        # Lookup the first parent which is not Tuple, List or Starred
        while True:
            node = node.parent
            if not hasattr(node, 'elts') and not hasattr(node, 'ctx'):
                return node
项目:ngx_status    作者:YoYoAdorkable    | 项目源码 | 文件源码
def _expand_tuples(self, args):
        for arg in args:
            if isinstance(arg, _ast.Tuple):
                for n in arg.elts:
                    yield n
            else:
                yield arg
项目:lambdazen    作者:brthor    | 项目源码 | 文件源码
def visit_FunctionDef(self, node):
        """
        :type node: _ast.FunctionDef
        """
        children = node.body
        lambda_assign_children = [child for child in children
                                if type(child) == _ast.Assign
                                    and len(child.targets) == 1
                                    and type(child.value) == _ast.Compare
                                    and (type(child.value.left) == _ast.Tuple or type(child.value.left) == _ast.Name)
                                    and all(map(lambda t: type(t) == _ast.Name, getattr(child.value.left, 'elts', [])))]

        # Support single line lambdas outside of assigns
        other_children = [child for child in children if child not in lambda_assign_children]
        for child in other_children:
            CompareNodeVisitor().visit(child)

        for assign_type_child in lambda_assign_children:
            arguments = _transform_function_arguments(assign_type_child.value.left)
            function_body = assign_type_child.value.comparators[0]

            if _is_multiline_lambda(function_body):
                all_statements = function_body.elts

                return_statement = all_statements[-1]
                statements = all_statements[0:len(all_statements) - 1]

                statements = _transform_multiline_assignment_statements(statements)
                return_statement = _transform_multiline_return_statement(return_statement)

                assign_target = assign_type_child.targets[0]
                if type(assign_target) is _ast.Attribute:
                    function_name = assign_target.attr
                else:
                    function_name = assign_target.id

                all_transformed_statements = statements + [return_statement]
                functiondef_object = ast.FunctionDef(args = arguments,
                                                     body=all_transformed_statements,
                                                     lineno=assign_type_child.lineno,
                                                     name=function_name,
                                                     col_offset=assign_type_child.col_offset,
                                                     decorator_list=[])

                children.insert(0, functiondef_object)
                assign_type_child.value = ast.Name(id=functiondef_object.name,
                                                   col_offset=functiondef_object.col_offset,
                                                   lineno=functiondef_object.lineno,
                                                   ctx=ast.Load())
            else:
                lambda_ast_transform = ast.Lambda(args=arguments,
                                                  body=function_body,
                                                  lineno=assign_type_child.lineno,
                                                  col_offset = assign_type_child.col_offset)
                assign_type_child.value = lambda_ast_transform

        return node
项目:bandit-ss    作者:zeroSteiner    | 项目源码 | 文件源码
def _get_literal_value(self, literal):
        '''Utility function to turn AST literals into native Python types

        :param literal: The AST literal to convert
        :return: The value of the AST literal
        '''
        if isinstance(literal, _ast.Num):
            literal_value = literal.n

        elif isinstance(literal, _ast.Str):
            literal_value = literal.s

        elif isinstance(literal, _ast.List):
            return_list = list()
            for li in literal.elts:
                return_list.append(self._get_literal_value(li))
            literal_value = return_list

        elif isinstance(literal, _ast.Tuple):
            return_tuple = tuple()
            for ti in literal.elts:
                return_tuple = return_tuple + (self._get_literal_value(ti),)
            literal_value = return_tuple

        elif isinstance(literal, _ast.Set):
            return_set = set()
            for si in literal.elts:
                return_set.add(self._get_literal_value(si))
            literal_value = return_set

        elif isinstance(literal, _ast.Dict):
            literal_value = dict(zip(literal.keys, literal.values))

        elif isinstance(literal, _ast.Ellipsis):
            # what do we want to do with this?
            literal_value = None

        elif isinstance(literal, _ast.Name):
            literal_value = literal.id

        # NOTE(sigmavirus24): NameConstants are only part of the AST in Python
        # 3. NameConstants tend to refer to things like True and False. This
        # prevents them from being re-assigned in Python 3.
        elif six.PY3 and isinstance(literal, _ast.NameConstant):
            literal_value = str(literal.value)

        # NOTE(sigmavirus24): Bytes are only part of the AST in Python 3
        elif six.PY3 and isinstance(literal, _ast.Bytes):
            literal_value = literal.s

        else:
            literal_value = None

        return literal_value