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


Python ast.JoinedStr方法代码示例

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


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

示例1: _evaluate_ast

# 需要导入模块: import ast [as 别名]
# 或者: from ast import JoinedStr [as 别名]
def _evaluate_ast(node):
    wrapper = None
    statement = ''

    if isinstance(node._bandit_parent, ast.BinOp):
        out = utils.concat_string(node, node._bandit_parent)
        wrapper = out[0]._bandit_parent
        statement = out[1]
    elif (isinstance(node._bandit_parent, ast.Attribute)
          and node._bandit_parent.attr == 'format'):
        statement = node.s
        # Hierarchy for "".format() is Wrapper -> Call -> Attribute -> Str
        wrapper = node._bandit_parent._bandit_parent._bandit_parent
    elif (hasattr(ast, 'JoinedStr')
          and isinstance(node._bandit_parent, ast.JoinedStr)):
        statement = node.s
        wrapper = node._bandit_parent._bandit_parent

    if isinstance(wrapper, ast.Call):  # wrapped in "execute" call?
        names = ['execute', 'executemany']
        name = utils.get_called_name(wrapper)
        return (name in names, statement)
    else:
        return (False, statement) 
开发者ID:PyCQA,项目名称:bandit,代码行数:26,代码来源:injection_sql.py

示例2: visit_Call

# 需要导入模块: import ast [as 别名]
# 或者: from ast import JoinedStr [as 别名]
def visit_Call(self, node: ast.Call):
        """
        Convert `ast.Call` to `ast.JoinedStr` f-string
        """

        match = matching_call(node)

        if match:
            state.call_candidates += 1

            # bail in these edge cases...
            if any(isinstance(arg, ast.Starred) for arg in node.args):
                return node

            result_node = joined_string(node)
            self.visit(result_node)
            self.counter += 1
            state.call_transforms += 1
            return result_node

        return node 
开发者ID:ikamensh,项目名称:flynt,代码行数:23,代码来源:FstringifyTransformer.py

示例3: transform_generic

# 需要导入模块: import ast [as 别名]
# 或者: from ast import JoinedStr [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

示例4: ast_formatted_value

# 需要导入模块: import ast [as 别名]
# 或者: from ast import JoinedStr [as 别名]
def ast_formatted_value(
    val, fmt_str: str = None, conversion=None
) -> ast.FormattedValue:
    if isinstance(val, ast.FormattedValue):
        return val

    if astor.to_source(val)[0] == "{":
        raise FlyntException(
            "values starting with '{' are better left not transformed."
        )

    if fmt_str:
        format_spec = ast.JoinedStr([ast_string_node(fmt_str.replace(":", ""))])
    else:
        format_spec = None

    if conversion is None:
        conversion = -1
    else:
        conversion = ord(conversion.replace("!", ""))
    return ast.FormattedValue(value=val, conversion=conversion, format_spec=format_spec) 
开发者ID:ikamensh,项目名称:flynt,代码行数:23,代码来源:transformer.py

示例5: visit_Call

# 需要导入模块: import ast [as 别名]
# 或者: from ast import JoinedStr [as 别名]
def visit_Call(self, node: ast.Call) -> Optional[ast.AST]:
        if isinstance(node.func, ast.Name):
            if node.func.id == "html":
                if (
                    not node.keywords
                    and len(node.args) == 1
                    and isinstance(node.args[0], ast.JoinedStr)
                ):
                    try:
                        new_node = self._transform_string(node.args[0])
                    except htm.ParseError as error:
                        raise DialectError(str(error), self.filename, node.lineno)
                    return self.generic_visit(
                        ast.fix_missing_locations(ast.copy_location(new_node, node))
                    )
        return node 
开发者ID:rmorshea,项目名称:idom,代码行数:18,代码来源:dialect.py

示例6: _transform_string

# 需要导入模块: import ast [as 别名]
# 或者: from ast import JoinedStr [as 别名]
def _transform_string(self, node: ast.JoinedStr) -> ast.Call:
        htm_strings: List[str] = []
        exp_nodes: List[ast.AST] = []
        for inner_node in node.values:
            if isinstance(inner_node, ast.Str):
                htm_strings.append(inner_node.s)
            elif isinstance(inner_node, ast.FormattedValue):
                if len(htm_strings) == len(exp_nodes):
                    htm_strings.append("")
                if inner_node.conversion != -1 or inner_node.format_spec:
                    exp_nodes.append(ast.JoinedStr([inner_node]))
                else:
                    exp_nodes.append(inner_node.value)

        call_stack = _HtmlCallStack()
        for op_type, *data in htm.htm_parse(htm_strings):
            getattr(self, f"_transform_htm_{op_type.lower()}")(
                exp_nodes, call_stack, *data
            )
        return call_stack.finish() 
开发者ID:rmorshea,项目名称:idom,代码行数:22,代码来源:dialect.py

示例7: supports_feature

# 需要导入模块: import ast [as 别名]
# 或者: from ast import JoinedStr [as 别名]
def supports_feature(feature):
  if feature == 'bytes_node':
    return hasattr(ast, 'Bytes') and issubclass(ast.Bytes, ast.AST)
  if feature == 'exec_node':
    return hasattr(ast, 'Exec') and issubclass(ast.Exec, ast.AST)
  if feature == 'type_annotations':
    try:
      ast.parse('def foo(bar: str=123) -> None: pass')
    except SyntaxError:
      return False
    return True
  if feature == 'fstring':
    return hasattr(ast, 'JoinedStr') and issubclass(ast.JoinedStr, ast.AST)
  # Python 2 counts tabs as 8 spaces for indentation
  if feature == 'mixed_tabs_spaces':
    return sys.version_info[0] < 3
  return False 
开发者ID:google,项目名称:pasta,代码行数:19,代码来源:test_utils.py

示例8: str_maker

# 需要导入模块: import ast [as 别名]
# 或者: from ast import JoinedStr [as 别名]
def str_maker(*strs: Tokenizer):
    head = strs[0]

    return ast.JoinedStr(**(loc @ head), values=list(map(_parse_expr, strs))) 
开发者ID:Xython,项目名称:YAPyPy,代码行数:6,代码来源:helper.py

示例9: transform_tuple

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

    Takes an ast.BinOp representing `"1. %s 2. %s" % (a, b)`
    and converted it to a ast.JoinedStr representing `f"1. {a} 2. {b}"`

    Args:
       node (ast.BinOp): The node to convert to a f-string

    Returns ast.JoinedStr (f-string)
    """

    format_str = node.left.s
    matches = VAR_KEY_PATTERN.findall(format_str)

    if len(node.right.elts) != len(matches):
        raise FlyntException("string formatting length mismatch")

    str_vars = deque(node.right.elts)

    segments = []
    blocks = deque(VAR_KEY_PATTERN.split(format_str))
    segments.append(ast_string_node(blocks.popleft().replace("%%", "%")))

    while len(blocks) > 0:

        fmt_prefix = blocks.popleft()
        fmt_spec = blocks.popleft()
        val = str_vars.popleft()

        fv = formatted_value(fmt_prefix, fmt_spec, val)

        segments.append(fv)
        segments.append(ast_string_node(blocks.popleft().replace("%%", "%")))

    return ast.JoinedStr(segments) 
开发者ID:ikamensh,项目名称:flynt,代码行数:38,代码来源:percent_transformer.py

示例10: visit_JoinedStr

# 需要导入模块: import ast [as 别名]
# 或者: from ast import JoinedStr [as 别名]
def visit_JoinedStr(self, node):
        new_vals = []
        for v in node.values:
            if (
                isinstance(v, ast.FormattedValue)
                and isinstance(v.value, ast.JoinedStr)
                and v.format_spec is None
            ):
                new_vals += v.value.values
            else:
                new_vals.append(v)

        node.values = new_vals
        return self.generic_visit(node) 
开发者ID:ikamensh,项目名称:flynt,代码行数:16,代码来源:fstr_lint.py

示例11: visit_BinOp

# 需要导入模块: import ast [as 别名]
# 或者: from ast import JoinedStr [as 别名]
def visit_BinOp(self, node: ast.BinOp):
        """
        Transforms a string concat to an f-string
        """
        if is_string_concat(node):
            self.counter += 1
            left, right = node.left, node.right
            left = self.visit(left)
            right = self.visit(right)

            if not check_sns_depth(left) or not check_sns_depth(right):
                node.left = left
                node.right = right
                return node

            parts = []
            for p in [left, right]:
                if isinstance(p, ast.JoinedStr):
                    parts += p.values
                else:
                    parts.append(p)

            segments = []
            for p in parts:
                if isinstance(p, ast.Constant):
                    segments.append(ast_string_node(p.value))
                else:
                    segments.append(ast_formatted_value(p))

            return ast.JoinedStr(segments)
        else:
            return self.generic_visit(node) 
开发者ID:ikamensh,项目名称:flynt,代码行数:34,代码来源:transformer.py

示例12: is_str_literal

# 需要导入模块: import ast [as 别名]
# 或者: from ast import JoinedStr [as 别名]
def is_str_literal(node):
    """ Returns True if a node is a string literal """
    if isinstance(node, ast.Constant):
        return isinstance(node.value, str)
    elif isinstance(node, ast.JoinedStr):
        return True
    else:
        return False 
开发者ID:ikamensh,项目名称:flynt,代码行数:10,代码来源:candidates.py

示例13: joined_str

# 需要导入模块: import ast [as 别名]
# 或者: from ast import JoinedStr [as 别名]
def joined_str(d: ast.JoinedStr):
    return "+".join(find(value) for value in d.values) 
开发者ID:timoniq,项目名称:vkbottle,代码行数:4,代码来源:definitions.py

示例14: visit_JoinedStr

# 需要导入模块: import ast [as 别名]
# 或者: from ast import JoinedStr [as 别名]
def visit_JoinedStr(self, node: ast.JoinedStr) -> None:
        """
        Forbids to use ``f`` strings.

        Raises:
            FormattedStringViolation

        """
        self.add_violation(consistency.FormattedStringViolation(node))
        self.generic_visit(node) 
开发者ID:wemake-services,项目名称:wemake-python-styleguide,代码行数:12,代码来源:builtins.py

示例15: test_ast_line_numbers

# 需要导入模块: import ast [as 别名]
# 或者: from ast import JoinedStr [as 别名]
def test_ast_line_numbers(self):
        expr = """
a = 10
f'{a * x()}'"""
        t = ast.parse(expr)
        self.assertEqual(type(t), ast.Module)
        self.assertEqual(len(t.body), 2)
        # check `a = 10`
        self.assertEqual(type(t.body[0]), ast.Assign)
        self.assertEqual(t.body[0].lineno, 2)
        # check `f'...'`
        self.assertEqual(type(t.body[1]), ast.Expr)
        self.assertEqual(type(t.body[1].value), ast.JoinedStr)
        self.assertEqual(len(t.body[1].value.values), 1)
        self.assertEqual(type(t.body[1].value.values[0]), ast.FormattedValue)
        self.assertEqual(t.body[1].lineno, 3)
        self.assertEqual(t.body[1].value.lineno, 3)
        self.assertEqual(t.body[1].value.values[0].lineno, 3)
        # check the binop location
        binop = t.body[1].value.values[0].value
        self.assertEqual(type(binop), ast.BinOp)
        self.assertEqual(type(binop.left), ast.Name)
        self.assertEqual(type(binop.op), ast.Mult)
        self.assertEqual(type(binop.right), ast.Call)
        self.assertEqual(binop.lineno, 3)
        self.assertEqual(binop.left.lineno, 3)
        self.assertEqual(binop.right.lineno, 3)
        self.assertEqual(binop.col_offset, 3)
        self.assertEqual(binop.left.col_offset, 3)
        self.assertEqual(binop.right.col_offset, 7) 
开发者ID:bkerler,项目名称:android_universal,代码行数:32,代码来源:test_fstring.py


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