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


Python ast.Tuple方法代码示例

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


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

示例1: version

# 需要导入模块: import ast [as 别名]
# 或者: from ast import Tuple [as 别名]
def version():
    path = 'pypika/__init__.py'
    with open(path, 'r') as file:
        t = compile(file.read(), path, 'exec', ast.PyCF_ONLY_AST)
        for node in (n for n in t.body if isinstance(n, ast.Assign)):
            if len(node.targets) == 1:
                name = node.targets[0]
                if isinstance(name, ast.Name) and \
                      name.id in ('__version__', '__version_info__', 'VERSION'):
                    v = node.value
                    if isinstance(v, ast.Str):
                        return v.s

                    if isinstance(v, ast.Tuple):
                        r = []
                        for e in v.elts:
                            if isinstance(e, ast.Str):
                                r.append(e.s)
                            elif isinstance(e, ast.Num):
                                r.append(str(e.n))
                        return '.'.join(r) 
开发者ID:kayak,项目名称:pypika,代码行数:23,代码来源:setup.py

示例2: visit_Yield

# 需要导入模块: import ast [as 别名]
# 或者: from ast import Tuple [as 别名]
def visit_Yield(self, node, *args):
        self.tree.hasYield += 1
        n = node.value
        self.visit(n)
        senslist = []
        if isinstance(n, ast.Tuple):
            for n in n.elts:
                if not isinstance(n.obj, (_Signal, _WaiterList)):
                    self.raiseError(node, _error.UnsupportedYield)
                senslist.append(n.obj)
        elif isinstance(n.obj, (_Signal, _WaiterList, delay)):
            senslist = [n.obj]
        elif _isMem(n.obj):
            senslist = n.obj
        else:
            self.raiseError(node, _error.UnsupportedYield)
        node.senslist = senslist 
开发者ID:myhdl,项目名称:myhdl,代码行数:19,代码来源:_analyze.py

示例3: convert_to_value

# 需要导入模块: import ast [as 别名]
# 或者: from ast import Tuple [as 别名]
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 PY2) and isinstance(item, ast.NameConstant):
        # None, True, False are nameconstants in python3, but names in 2
        return item.value
    else:
        return UnhandledKeyType() 
开发者ID:AtomLinter,项目名称:linter-pylama,代码行数:27,代码来源:checker.py

示例4: TRY

# 需要导入模块: import ast [as 别名]
# 或者: from ast import Tuple [as 别名]
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') 
开发者ID:AtomLinter,项目名称:linter-pylama,代码行数:21,代码来源:checker.py

示例5: _get_value_from_ast

# 需要导入模块: import ast [as 别名]
# 或者: from ast import Tuple [as 别名]
def _get_value_from_ast(self, obj):
        """
        Return the value of the ast object.
        """
        if isinstance(obj, ast.Num):
            return obj.n
        elif isinstance(obj, ast.Str):
            return obj.s
        elif isinstance(obj, ast.List):
            return [self._get_value_from_ast(e) for e in obj.elts]
        elif isinstance(obj, ast.Tuple):
            return tuple([self._get_value_from_ast(e) for e in obj.elts])

        # None, True and False are NameConstants in Py3.4 and above.
        elif sys.version_info.major >= 3 and isinstance(obj, ast.NameConstant):
            return obj.value

        # For python versions below 3.4
        elif isinstance(obj, ast.Name) and (obj.id in ["True", "False", "None"]):
            return string_to_constant[obj.id]

        # Probably passed a variable name.
        # Or passed a single word without wrapping it in quotes as an argument
        # ex: p.inflect("I plural(see)") instead of p.inflect("I plural('see')")
        raise NameError("name '%s' is not defined" % obj.id) 
开发者ID:bids-standard,项目名称:pybids,代码行数:27,代码来源:inflect.py

示例6: visit_Call

# 需要导入模块: import ast [as 别名]
# 或者: from ast import Tuple [as 别名]
def visit_Call(self, node: ast.Call) -> None:
        if (
                isinstance(node.func, ast.Name) and
                node.func.id == 'set' and
                len(node.args) == 1 and
                not node.keywords and
                isinstance(node.args[0], SET_TRANSFORM)
        ):
            arg, = node.args
            key = _ast_to_offset(node.func)
            if isinstance(arg, (ast.List, ast.Tuple)) and not arg.elts:
                self.set_empty_literals[key] = arg
            else:
                self.sets[key] = arg
        elif (
                isinstance(node.func, ast.Name) and
                node.func.id == 'dict' and
                len(node.args) == 1 and
                not node.keywords and
                isinstance(node.args[0], (ast.ListComp, ast.GeneratorExp)) and
                isinstance(node.args[0].elt, (ast.Tuple, ast.List)) and
                len(node.args[0].elt.elts) == 2
        ):
            self.dicts[_ast_to_offset(node.func)] = node.args[0]
        self.generic_visit(node) 
开发者ID:asottile,项目名称:pyupgrade,代码行数:27,代码来源:pyupgrade.py

示例7: visit_Try

# 需要导入模块: import ast [as 别名]
# 或者: from ast import Tuple [as 别名]
def visit_Try(self, node: ast.Try) -> None:
        for handler in node.handlers:
            htype = handler.type
            if self._is_os_error_alias(htype):
                assert isinstance(htype, (ast.Name, ast.Attribute))
                self.os_error_alias_simple[_ast_to_offset(htype)] = htype
            elif (
                    isinstance(htype, ast.Tuple) and
                    any(
                        self._is_os_error_alias(elt)
                        for elt in htype.elts
                    )
            ):
                self.os_error_alias_excepts.add(_ast_to_offset(htype))

        self.generic_visit(node) 
开发者ID:asottile,项目名称:pyupgrade,代码行数:18,代码来源:pyupgrade.py

示例8: _compare_to_3

# 需要导入模块: import ast [as 别名]
# 或者: from ast import Tuple [as 别名]
def _compare_to_3(
        test: ast.Compare,
        op: Union[Type[ast.cmpop], Tuple[Type[ast.cmpop], ...]],
    ) -> bool:
        if not (
                isinstance(test.ops[0], op) and
                isinstance(test.comparators[0], ast.Tuple) and
                len(test.comparators[0].elts) >= 1 and
                all(isinstance(n, ast.Num) for n in test.comparators[0].elts)
        ):
            return False

        # checked above but mypy needs help
        elts = cast('List[ast.Num]', test.comparators[0].elts)

        return elts[0].n == 3 and all(n.n == 0 for n in elts[1:]) 
开发者ID:asottile,项目名称:pyupgrade,代码行数:18,代码来源:pyupgrade.py

示例9: visit_Try

# 需要导入模块: import ast [as 别名]
# 或者: from ast import Tuple [as 别名]
def visit_Try(self, node):
        def any_import_error(items):
            for item in items:
                if isinstance(item, ast.Name) and item.id in {
                    "ModuleNotFoundError",
                    "ImportError",
                }:
                    return True
                elif isinstance(item, ast.Tuple) and any_import_error(
                    item.elts
                ):
                    return True
            else:
                return False

        self.any_import_error = any_import_error(
            handle.type for handle in node.handlers
        )
        self.generic_visit(node)
        self.any_import_error = False 
开发者ID:hakancelik96,项目名称:unimport,代码行数:22,代码来源:scan.py

示例10: get_list_tuple_names

# 需要导入模块: import ast [as 别名]
# 或者: from ast import Tuple [as 别名]
def get_list_tuple_names(node):
    """Get all names of a tuple or list. Recursive method.

    Args:
        node: a ast.Tuple or ast.List node

    Returns: a list of all names of the tuple

    """
    assert isinstance(node, (ast.Tuple, ast.List))
    names = list()
    for _n in node.elts:
        if isinstance(_n, (ast.Tuple, ast.List)):
            # recursive call
            names.extend(get_list_tuple_names(_n))
        elif isinstance(_n, (ast.Name,)):
            names.append(_n.id)
    return names 
开发者ID:kubeflow-kale,项目名称:kale,代码行数:20,代码来源:ast.py

示例11: transform2call

# 需要导入模块: import ast [as 别名]
# 或者: from ast import Tuple [as 别名]
def transform2call(var):
    if isinstance(var, ast.BinOp):
        is_mod = isinstance(var.op, ast.Mod)
        is_left_str = isinstance(var.left, ast.Str)
        if is_mod and is_left_str:
            new_call = ast.Call()
            new_call.args = []
            new_call.args = []
            if six.PY2:
                new_call.starargs = None
            new_call.keywords = None
            if six.PY2:
                new_call.kwargs = None
            new_call.lineno = var.lineno
            new_call.func = ast.Attribute()
            new_call.func.value = var.left
            new_call.func.attr = 'format'
            if isinstance(var.right, ast.Tuple):
                new_call.args = var.right.elts
            elif six.PY2 and isinstance(var.right, ast.Dict):
                new_call.kwargs = var.right
            else:
                new_call.args = [var.right]
            return new_call 
开发者ID:PyCQA,项目名称:bandit,代码行数:26,代码来源:django_xss.py

示例12: transform_generic

# 需要导入模块: import ast [as 别名]
# 或者: from ast import Tuple [as 别名]
def transform_generic(node):
    """Convert a `BinOp` `%` formatted str with a unknown name on the `node.right` to an f-string.

    When `node.right` is a Name since we don't know if it's a single var or a dict so we sniff the string.

    Sniffs the left string for Dict style usage
    e.g. `"val: %(key_name1)s val2: %(key_name2)s" % some_dict`

    else (e.g. `"val: %s" % some_var`):
    Borrow the core logic by injecting the name into a ast.Tuple

    Returns ast.JoinedStr (f-string), bool: str-in-str
    """

    has_dict_str_format = DICT_PATTERN.findall(node.left.s)
    if has_dict_str_format:
        return transform_dict(node), True

    # if it's just a name then pretend it's tuple to use that code
    node.right = ast.Tuple(elts=[node.right])
    return transform_tuple(node), False 
开发者ID:ikamensh,项目名称:flynt,代码行数:23,代码来源:percent_transformer.py

示例13: check_for_loop

# 需要导入模块: import ast [as 别名]
# 或者: from ast import Tuple [as 别名]
def check_for_loop(self, statement):
        stack = [statement.target]
        while stack:
            item = stack.pop()
            if isinstance(item, (ast.Tuple, ast.List)):
                stack.extend(list(item.elts))
            elif isinstance(item, ast.Name) and \
                    item.id in BUILTINS:
                yield self.error(statement, variable=item.id)
            elif PY3 and isinstance(item, ast.Starred):
                if hasattr(item.value, 'id') and item.value.id in BUILTINS:
                    yield self.error(
                        statement,
                        variable=item.value.id,
                    )
                elif hasattr(item.value, 'elts'):
                    stack.extend(list(item.value.elts)) 
开发者ID:gforcada,项目名称:flake8-builtins,代码行数:19,代码来源:flake8_builtins.py

示例14: visit_Assign

# 需要导入模块: import ast [as 别名]
# 或者: from ast import Tuple [as 别名]
def visit_Assign(self, node: ast.Assign) -> None:
        for target in node.targets:
            if isinstance(target, ast.Name):
                self.define(target.id, node)

        if (
                len(node.targets) == 1 and
                isinstance(node.targets[0], ast.Name) and
                node.targets[0].id == '__all__' and
                isinstance(node.value, (ast.Tuple, ast.List))
        ):
            for elt in node.value.elts:
                if isinstance(elt, ast.Str):
                    self.read(elt.s, elt)

        self.generic_visit(node)

    # TODO: AnnAssign 
开发者ID:asottile,项目名称:dead,代码行数:20,代码来源:dead.py

示例15: visit_comment

# 需要导入模块: import ast [as 别名]
# 或者: from ast import Tuple [as 别名]
def visit_comment(self, lineno: int, line: str) -> None:
        if DISABLE_COMMENT_RE.search(line):
            self.disabled.add(self._file_line(self.filename, lineno))

        if not TYPE_COMMENT_RE.match(line) or TYPE_IGNORE_RE.match(line):
            return

        line = line.split(':', 1)[1].strip()
        func_match = TYPE_FUNC_RE.match(line)
        if not func_match:
            parts: Tuple[str, ...] = (line,)
        else:
            parts = (
                func_match.group(1).replace('*', ''),
                func_match.group(2).strip(),
            )

        for part in parts:
            ast_obj = ast.parse(part, f'<{self.filename}:{lineno}: comment>')
            # adjust the line number to be that of the comment
            for descendant in ast.walk(ast_obj):
                if 'lineno' in descendant._attributes:
                    descendant.lineno = lineno

            self.visit(ast_obj) 
开发者ID:asottile,项目名称:dead,代码行数:27,代码来源:dead.py


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