Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
def visit_Yield(self, node):
with self.delimit(node):
set_precedence(get_op_precedence(node) + 1, node.value)
self.write('yield')
self.conditional_write(' ', node.value)
def pre_Lambda(self):
""" Set a low, yet higher than no, precedence for our
subnodes to see, and force parentheses on this node
if it is inside any sort of expression.
We could probably optimize a few more cases where
we don't need parenthese, but lambdas and IfExprs
are rare enough, it's probably good to have them
for clarity anyway.
"""
node = self.cur_node
node._precedence = get_op_precedence(node)
node._use_parens = getattr(self.parent, '_precedence', -1) > -1
pre_IfExp = pre_Lambda
def pre_Attribute(self):
"""Set attribute to a really high precedence so
that we force parentheses around any lhs
expression. Same thing for comprehensions
and calls.
"""
node = self.cur_node
node._precedence = get_op_precedence(node)
pre_comprehension = pre_Attribute
def set_precedence(self, node, op, subnodes=(), bump0=0, bump1=0):
"""Generic precedence setter -- handles incrementing
precedence before processing subnodes.
"""
precedence = get_op_precedence(op) if not isinstance(op, int) else op
parent_precedence = getattr(self.parent, '_precedence', -1)
node._use_parens = precedence < parent_precedence
if subnodes:
node._precedence = precedence + bump0
self.walk(subnodes[0])
node._precedence = precedence + bump1
for node in subnodes[1:]:
self.walk(node)
# If we did the subnodes, do not recurse any further
return subnodes
def pre_Compare(self):
""" Comparison ops _should_ all have the same precedence.
We bump the precedence to handle stuff like
(a < b) != (c < d)
"""
node = self.cur_node
# These should all be the same...
precedence, = set(get_op_precedence(x) for x in node.ops)
subnodes = [node.left] + node.comparators
return self.set_precedence(node, precedence, subnodes, 1, 1)
def pre_Num(self):
"""There are two reasons we might need to place
parentheses around a number:
-- Exponentiation binds more tightly than a unary '-',
so if a literal number looks like it has a unary '-',
we should use parentheses.
-- If we are accessing an attribute of a literal number,
the '.' could be confused for the definition of
a literal float.
"""
parent_precedence = getattr(self.parent, '_precedence', -1)
node = self.cur_node
precedence = get_op_precedence(node)
node._use_parens = precedence < parent_precedence
node = None
op = None
for arg in args:
if isinstance(arg, ast.AST):
if node is None:
node = arg
else:
op = arg
else:
delimiters = arg
tree.write(delimiters[0])
result = self.result = tree.result
self.index = len(result)
self.closing = delimiters[1]
if node is not None:
self.p = p = get_op_precedence(op or node)
self.pp = pp = tree.get__pp(node)
self.discard = p >= pp