本文整理匯總了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)
示例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
示例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
示例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)
示例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
示例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()
示例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
示例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)))
示例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)
示例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)
示例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)
示例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
示例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)
示例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)
示例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)