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


Python ast.FormattedValue方法代码示例

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


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

示例1: ast_formatted_value

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

    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,代码行数:21,代码来源:format_call_transforms.py

示例2: ast_formatted_value

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

示例3: visit_JoinedStr

# 需要导入模块: import ast [as 别名]
# 或者: from ast import FormattedValue [as 别名]
def visit_JoinedStr(self, node):
    self.__fstrings = True
    self.__vvprint("f-strings require 3.6+")
    if hasattr(node, "values"):
      total = len(node.values)
      for i in range(total):
        val = node.values[i]
        # A self-referencing f-string will be at the end of the Constant, like "..stuff..expr=", and
        # the next value will be a FormattedValue(value=..) with Names or nested Calls with Names
        # inside, for instance.
        if isinstance(val, ast.Constant) and hasattr(val, "value") and \
           isinstance(val.value, str) and val.value.strip().endswith("=") and i + 1 < total:
            next_val = node.values[i + 1]
            if isinstance(next_val, ast.FormattedValue):
              fstring_value =\
                self.__trim_fstring_value(self.__extract_fstring_value(next_val.value))
              if len(fstring_value) > 0 and\
                self.__trim_fstring_value(val.value).endswith(fstring_value + "="):
                  self.__fstrings_self_doc = True
                  self.__vvprint("self-documenting fstrings require 3.8+")
                  break

    self.generic_visit(node)

  # Mark variable names as aliases. 
开发者ID:netromdk,项目名称:vermin,代码行数:27,代码来源:source_visitor.py

示例4: _transform_string

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

示例5: visit_JoinedStr

# 需要导入模块: import ast [as 别名]
# 或者: from ast import FormattedValue [as 别名]
def visit_JoinedStr(self, node):
    """Annotate a JoinedStr node with the fstr formatting metadata."""
    fstr_iter = self.tokens.fstr()()
    res = ''
    values = (v for v in node.values if isinstance(v, ast.FormattedValue))
    while True:
      res_part, tg = next(fstr_iter)
      res += res_part
      if tg is None:
        break
      prev_tokens = self.tokens
      self.tokens = tg
      self.visit(next(values))
      self.tokens = prev_tokens

    self.attr(node, 'content', [lambda: res], default=res) 
开发者ID:google,项目名称:pasta,代码行数:18,代码来源:annotate.py

示例6: visit_JoinedStr

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

示例7: JOINEDSTR

# 需要导入模块: import ast [as 别名]
# 或者: from ast import FormattedValue [as 别名]
def JOINEDSTR(self, node):
        if (
                # the conversion / etc. flags are parsed as f-strings without
                # placeholders
                not self._in_fstring and
                not any(isinstance(x, ast.FormattedValue) for x in node.values)
        ):
            self.report(messages.FStringMissingPlaceholders, node)

        self._in_fstring, orig = True, self._in_fstring
        try:
            self.handleChildren(node)
        finally:
            self._in_fstring = orig 
开发者ID:PyCQA,项目名称:pyflakes,代码行数:16,代码来源:checker.py

示例8: test_no_fstrings

# 需要导入模块: import ast [as 别名]
# 或者: from ast import FormattedValue [as 别名]
def test_no_fstrings():
    from pathlib import Path
    import ast
    py_paths = list((Path().absolute().parent / 'kpa').rglob('*.py'))
    for py_path in py_paths:
        parsed = ast.parse(py_path.read_text())
        for node in ast.walk(parsed):
            assert not isinstance(node, ast.FormattedValue), (py_path, node.lineno) 
开发者ID:statgen,项目名称:pheweb,代码行数:10,代码来源:test_no_fstrings.py

示例9: formatted_value

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

示例10: visit_JoinedStr

# 需要导入模块: import ast [as 别名]
# 或者: from ast import FormattedValue [as 别名]
def visit_JoinedStr (self, node):
        self.emit (repr (''.join ([value.s if type (value) == ast.Str else '{{}}' for value in node.values])))
        self.emit ('.format (')
        index = 0
        for value in node.values:
            if type (value) == ast.FormattedValue:
                self.emitComma (index)
                self.visit (value)
                index += 1
        self.emit (')') 
开发者ID:QQuick,项目名称:Transcrypt,代码行数:12,代码来源:compiler.py

示例11: fstring_expression

# 需要导入模块: import ast [as 别名]
# 或者: from ast import FormattedValue [as 别名]
def fstring_expression(f):
  """Decorates a function where the node is a FormattedValue in an fstring."""
  return _gen_wrapper(f, scope=False) 
开发者ID:google,项目名称:pasta,代码行数:5,代码来源:annotate.py

示例12: get_formatted_values

# 需要导入模块: import ast [as 别名]
# 或者: from ast import FormattedValue [as 别名]
def get_formatted_values(joined_str):
  """Get all FormattedValues from a JoinedStr, in order."""
  return [v for v in joined_str.values if isinstance(v, ast.FormattedValue)] 
开发者ID:google,项目名称:pasta,代码行数:5,代码来源:fstring_utils.py

示例13: placeholder

# 需要导入模块: import ast [as 别名]
# 或者: from ast import FormattedValue [as 别名]
def placeholder(val_index):
  """Get the placeholder token for a FormattedValue in an fstring."""
  return _FSTRING_VAL_PLACEHOLDER.format(index=val_index) 
开发者ID:google,项目名称:pasta,代码行数:5,代码来源:fstring_utils.py

示例14: test_ast_line_numbers

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

示例15: get_kernel_embed

# 需要导入模块: import ast [as 别名]
# 或者: from ast import FormattedValue [as 别名]
def get_kernel_embed():
        """A list of kernel embed nodes

        Returns:
            nodes (list): AST nodes which form the following code.

            ```
            import os
            pid = os.fork()
            if os.fork() == 0:
                open(f'{os.environ["HOME"]}/.pynt', 'a').close()
                import IPython
                IPython.start_kernel(user_ns={**locals(), **globals(), **vars()})
            os.waitpid(pid, 0)
            ```

        This is a purely functional method which always return the same thing.

        """
        return [
            ast.Import(names=[ast.alias(name='os', asname=None),]),
            ast.Assign(targets=[ast.Name(id='pid', ctx=ast.Store()),], value=ast.Call(func=ast.Attribute(value=ast.Name(id='os', ctx=ast.Load()), attr='fork', ctx=ast.Load()), args=[], keywords=[])),
            ast.If(
                test=ast.Compare(left=ast.Name(id='pid', ctx=ast.Load()), ops=[ast.Eq(),], comparators=[ast.Num(n=0),]),
                body=[
                    ast.Expr(value=ast.Call(func=ast.Attribute(value=ast.Call(func=ast.Name(id='open', ctx=ast.Load()), args=[
                        ast.JoinedStr(values=[
                            ast.FormattedValue(value=ast.Subscript(value=ast.Attribute(value=ast.Name(id='os', ctx=ast.Load()), attr='environ', ctx=ast.Load()), slice=ast.Index(value=ast.Str(s='HOME')), ctx=ast.Load()), conversion=-1, format_spec=None),
                            ast.Str(s='/.pynt'),
                        ]),
                        ast.Str(s='a'),
                    ], keywords=[]), attr='close', ctx=ast.Load()), args=[], keywords=[])),
                    ast.Import(names=[
                        ast.alias(name='IPython', asname=None),
                    ]),
                    ast.Expr(value=ast.Call(func=ast.Attribute(value=ast.Name(id='IPython', ctx=ast.Load()), attr='start_kernel', ctx=ast.Load()), args=[], keywords=[
                        ast.keyword(arg='user_ns', value=ast.Dict(keys=[
                            None,
                            None,
                            None,
                        ], values=[
                            ast.Call(func=ast.Name(id='locals', ctx=ast.Load()), args=[], keywords=[]),
                            ast.Call(func=ast.Name(id='globals', ctx=ast.Load()), args=[], keywords=[]),
                            ast.Call(func=ast.Name(id='vars', ctx=ast.Load()), args=[], keywords=[]),
                        ])),
                    ])),
            ], orelse=[]),
            ast.Expr(value=ast.Call(func=ast.Attribute(value=ast.Name(id='os', ctx=ast.Load()), attr='waitpid', ctx=ast.Load()), args=[
                ast.Name(id='pid', ctx=ast.Load()),
                ast.Num(n=0),
            ], keywords=[])),
        ] 
开发者ID:ebanner,项目名称:pynt,代码行数:54,代码来源:node_transformers.py


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