Python ast.USub() Examples
The following are 30
code examples of ast.USub().
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
ast
, or try the search function
.
Example #1
Source File: topython.py From pyrser with GNU General Public License v3.0 | 6 votes |
def visit_Hook(self, node: parsing.Hook) -> ast.expr: """Generates python code calling a hook. self.evalHook('hookname', self.ruleNodes[-1]) """ return ast.Call( ast.Attribute( ast.Name('self', ast.Load()), 'evalHook', ast.Load()), [ ast.Str(node.name), ast.Subscript( ast.Attribute( ast.Name('self', ast.Load()), 'ruleNodes', ast.Load()), ast.Index(ast.UnaryOp(ast.USub(), ast.Num(1))), ast.Load())], [], None, None)
Example #2
Source File: _toVHDL.py From myhdl with GNU Lesser General Public License v2.1 | 6 votes |
def visit_UnaryOp(self, node): # in python3 a negative Num is represented as an USub of a positive Num # Fix: restore python2 behavior by a shortcut: invert value of Num, inherit # vhdl type from UnaryOp node, and visit the modified operand if isinstance(node.op, ast.USub) and isinstance(node.operand, ast.Num): node.operand.n = -node.operand.n node.operand.vhd = node.vhd self.visit(node.operand) return pre, suf = self.inferCast(node.vhd, node.vhdOri) self.write(pre) self.write("(") self.write(opmap[type(node.op)]) self.visit(node.operand) self.write(")") self.write(suf)
Example #3
Source File: _toVHDL.py From myhdl with GNU Lesser General Public License v2.1 | 6 votes |
def visit_UnaryOp(self, node): self.visit(node.operand) node.vhd = copy(node.operand.vhd) if isinstance(node.op, ast.Not): # postpone this optimization until initial values are written # if isinstance(node.operand.vhd, vhd_std_logic): # node.vhd = vhd_std_logic() # else: # node.vhd = node.operand.vhd = vhd_boolean() node.vhd = node.operand.vhd = vhd_boolean() elif isinstance(node.op, ast.USub): if isinstance(node.vhd, vhd_unsigned): node.vhd = vhd_signed(node.vhd.size + 1) elif isinstance(node.vhd, vhd_nat): node.vhd = vhd_int() node.vhdOri = copy(node.vhd)
Example #4
Source File: pre_processing.py From sspam with BSD 3-Clause "New" or "Revised" License | 6 votes |
def visit_UnaryOp(self, node): 'Change -x to (-1)*x' self.generic_visit(node) if isinstance(node.op, ast.USub): ope = node.operand cond_mult = (isinstance(ope, ast.BinOp) and isinstance(ope.op, ast.Mult)) if cond_mult: if isinstance(ope.left, ast.Num): node = ast.BinOp(ast.Num(-ope.left.n), ast.Mult(), ope.right) elif isinstance(ope.right, ast.Num): node = ast.BinOp(ope.left, ast.Mult(), ast.Num(-ope.right.n)) else: node = ast.BinOp(ast.Num(-1), ast.Mult(), ope) else: node = ast.BinOp(ast.Num(-1), ast.Mult(), ope) return node
Example #5
Source File: _ast_to_ir2.py From tmppy with Apache License 2.0 | 6 votes |
def unary_minus_expression_ast_to_ir2(ast_node: ast.UnaryOp, compilation_context: CompilationContext, in_match_pattern: bool, check_var_reference: Callable[[ast.Name], None], match_lambda_argument_names: Set[str], current_stmt_line: int): assert isinstance(ast_node.op, ast.USub) if in_match_pattern: raise CompilationError(compilation_context, ast_node, 'The "-" operator is not allowed in match patterns') expr = expression_ast_to_ir2(ast_node.operand, compilation_context, in_match_pattern, check_var_reference, match_lambda_argument_names, current_stmt_line) if expr.expr_type != ir2.IntType(): raise CompilationError(compilation_context, ast_node.operand, 'The "-" operator is only supported for ints, but this value has type %s.' % str(expr.expr_type)) return ir2.IntUnaryMinusExpr(expr=expr)
Example #6
Source File: operators.py From wemake-python-styleguide with MIT License | 6 votes |
def _get_non_negative_nodes( self, left: Optional[ast.AST], right: Optional[ast.AST] = None, ): non_negative_numbers = [] for node in filter(None, (left, right)): real_node = unwrap_unary_node(node) correct_node = ( isinstance(real_node, ast.Num) and real_node.n in self._meaningless_operations and not (real_node.n == 1 and walk.is_contained(node, ast.USub)) ) if correct_node: non_negative_numbers.append(real_node) return non_negative_numbers
Example #7
Source File: parser.py From vecpy with MIT License | 5 votes |
def unaryop(self, block, node): operand = self.expression(block, node.operand) if isinstance(node.op, ast.UAdd): #No-Op var = operand elif isinstance(node.op, ast.USub): if operand.value is not None: #It's a literal, return the negation var = self.add_literal(-operand.value) else: #It's an expression, subtract from zero (faster than multiplying by -1) var = self.add_variable(None) zero = self.add_literal(0, 'ZERO') operation = BinaryOperation(zero, Operator.subtract, operand) assignment = Assignment(var, operation) block.add(assignment) elif isinstance(node.op, ast.Invert): #Make sure it's numeric if operand.is_mask: raise Exception('Unary invert requires a numeric operand') #Bit-flip var = self.add_variable(None) operation = UnaryOperation(Operator.bit_not, operand) assignment = Assignment(var, operation) block.add(assignment) elif isinstance(node.op, ast.Not): #Make sure it's boolean if not operand.is_mask: raise Exception('Unary not requires a boolean operand') #Invert the mask var = self.add_variable(None, is_mask=True) operation = UnaryOperation(Operator.bool_not, operand) assignment = Assignment(var, operation) block.add(assignment) else: raise Exception('Unexpected UnaryOp (%s)'%(node.op.__class__)) return var #Parses a comparison operator (AST CmpOp)
Example #8
Source File: yacc.py From yaksok with BSD 3-Clause "New" or "Revised" License | 5 votes |
def p_unary_expr_minus_primary(t): #'''unary_expr : MINUS primary %prec UMINUS''' '''unary_expr : MINUS primary''' usub = ast.USub() usub.lineno = t.lineno(1) usub.col_offset = -1 # XXX t[0] = ast.UnaryOp(usub, t[2]) t[0].lineno = t.lineno(2) t[0].col_offset = -1 # XXX
Example #9
Source File: pytables.py From Splunking-Crime with GNU Affero General Public License v3.0 | 5 votes |
def visit_UnaryOp(self, node, **kwargs): if isinstance(node.op, (ast.Not, ast.Invert)): return UnaryOp('~', self.visit(node.operand)) elif isinstance(node.op, ast.USub): return self.const_type(-self.visit(node.operand).value, self.env) elif isinstance(node.op, ast.UAdd): raise NotImplementedError('Unary addition not supported')
Example #10
Source File: utils.py From Splunking-Crime with GNU Affero General Public License v3.0 | 5 votes |
def visitUnaryOp(self, node): import ast if isinstance(node.op, ast.UAdd): return +self.visit(node.operand) elif isinstance(node.op, ast.USub): return -self.visit(node.operand) else: raise SyntaxError("Unknown unary op: %r" % node.op)
Example #11
Source File: hgawk_grammar.py From histogrammar-python with Apache License 2.0 | 5 votes |
def p_factor_2(p): '''factor : MINUS factor''' # 1 2 if isinstance(p[2], ast.Num) and not hasattr(p[2], "unary"): p[2].n *= -1 p[0] = p[2] p[0].unary = True inherit_lineno(p[0], p[1][1]) else: op = ast.USub(rule=inspect.currentframe().f_code.co_name, **p[1][1]) p[0] = ast.UnaryOp(op, p[2], rule=inspect.currentframe().f_code.co_name) inherit_lineno(p[0], op)
Example #12
Source File: utils.py From ImageFusion with MIT License | 5 votes |
def visitUnaryOp(self, node): import ast if isinstance(node.op, ast.UAdd): return +self.visit(node.operand) elif isinstance(node.op, ast.USub): return -self.visit(node.operand) else: raise SyntaxError("Unknown unary op: %r" % node.op)
Example #13
Source File: bird.py From executing with MIT License | 5 votes |
def is_interesting_expression(node): # type: (ast.AST) -> bool """ If this expression has a value that may not be exactly what it looks like, return True. Put differently, return False if this is just a literal. """ return (isinstance(node, ast.expr) and not (isinstance(node, (ast.Num, ast.Str, getattr(ast, 'NameConstant', ()))) or isinstance(getattr(node, 'ctx', None), (ast.Store, ast.Del)) or (isinstance(node, ast.UnaryOp) and isinstance(node.op, (ast.UAdd, ast.USub)) and isinstance(node.operand, ast.Num)) or (isinstance(node, (ast.List, ast.Tuple, ast.Dict)) and not any(is_interesting_expression(n) for n in ast.iter_child_nodes(node)))))
Example #14
Source File: pytables.py From elasticintel with GNU General Public License v3.0 | 5 votes |
def visit_UnaryOp(self, node, **kwargs): if isinstance(node.op, (ast.Not, ast.Invert)): return UnaryOp('~', self.visit(node.operand)) elif isinstance(node.op, ast.USub): return self.const_type(-self.visit(node.operand).value, self.env) elif isinstance(node.op, ast.UAdd): raise NotImplementedError('Unary addition not supported')
Example #15
Source File: source_visitor.py From vermin with MIT License | 5 votes |
def __is_neg_int(self, node): return (isinstance(node, ast.Num) and isinstance(node.n, int) and node.n < 0) or \ (isinstance(node, ast.UnaryOp) and isinstance(node.op, ast.USub) and isinstance(node.operand, ast.Num) and isinstance(node.operand.n, int))
Example #16
Source File: annotation.py From vyper with Apache License 2.0 | 5 votes |
def visit_UnaryOp(self, node): """ Adjust operand value and discard unary operations, where possible. This is done so that negative decimal literals are accurately represented. """ self.generic_visit(node) # TODO once grammar is updated, remove this # UAdd has no effect on the value of it's operand, so it is discarded if isinstance(node.op, python_ast.UAdd): return node.operand is_sub = isinstance(node.op, python_ast.USub) is_num = ( hasattr(node.operand, "n") and not isinstance(node.operand.n, bool) and isinstance(node.operand.n, (int, Decimal)) ) if is_sub and is_num: node.operand.n = 0 - node.operand.n node.operand.col_offset = node.col_offset node.operand.node_source_code = node.node_source_code return node.operand else: return node
Example #17
Source File: utils.py From mxnet-lambda with Apache License 2.0 | 5 votes |
def visitUnaryOp(self, node): import ast if isinstance(node.op, ast.UAdd): return +self.visit(node.operand) elif isinstance(node.op, ast.USub): return -self.visit(node.operand) else: raise SyntaxError("Unknown unary op: %r" % node.op)
Example #18
Source File: _recompute.py From icontract with MIT License | 5 votes |
def visit_UnaryOp(self, node: ast.UnaryOp) -> Any: """Visit the node operand and apply the operation on the result.""" if isinstance(node.op, ast.UAdd): result = +self.visit(node=node.operand) elif isinstance(node.op, ast.USub): result = -self.visit(node=node.operand) elif isinstance(node.op, ast.Not): result = not self.visit(node=node.operand) elif isinstance(node.op, ast.Invert): result = ~self.visit(node=node.operand) else: raise NotImplementedError("Unhandled op of {}: {}".format(node, node.op)) self.recomputed_values[node] = result return result
Example #19
Source File: ast_translator.py From pseudo-python with MIT License | 5 votes |
def _translate_unaryop(self, operand, op, location): value = operand if isinstance(op, ast.USub): value_node = self._translate_node(value) if value_node['pseudo_type'] != 'Int' and value_node['pseudo_type'] != 'Float': raise type_check_error('- expects Int or Float', location, self.lines[location[0]], wrong_type=value_node['pseudo_type']) if value_node['type'] == 'int': return { 'type': 'int', 'value': -value_node['value'], 'pseudo_type': 'Int' } else: return { 'type': 'unary_op', 'op': '-', 'value': value_node, 'pseudo_type': value_node['pseudo_type'] } elif isinstance(op, ast.Not): value_node = self._testable(self._translate_node(value)) if value_node['type'] == 'standard_method_call' and value_node['message'] == 'present?': value_node['message'] = 'empty?' return value_node else: return { 'type': 'unary_op', 'op': 'not', 'value': value_node, 'pseudo_type': 'Boolean' } else: raise translation_error('no support for %s as an unary op' % type(op).__name__, location, self.lines[location[0]], suggestions='not and - are supported')
Example #20
Source File: common.py From fdroidserver with GNU Affero General Public License v3.0 | 5 votes |
def calculate_math_string(expr): ops = { ast.Add: operator.add, ast.Mult: operator.mul, ast.Sub: operator.sub, ast.USub: operator.neg, } def execute_ast(node): if isinstance(node, ast.Num): # <number> return node.n elif isinstance(node, ast.BinOp): # <left> <operator> <right> return ops[type(node.op)](execute_ast(node.left), execute_ast(node.right)) elif isinstance(node, ast.UnaryOp): # <operator> <operand> e.g., -1 return ops[type(node.op)](ast.literal_eval(node.operand)) else: raise SyntaxError(node) try: if '#' in expr: raise SyntaxError('no comments allowed') return execute_ast(ast.parse(expr, mode='eval').body) except SyntaxError: raise SyntaxError("could not parse expression '{expr}', " "only basic math operations are allowed (+, -, *)" .format(expr=expr))
Example #21
Source File: utils.py From elasticintel with GNU General Public License v3.0 | 5 votes |
def visitUnaryOp(self, node): import ast if isinstance(node.op, ast.UAdd): return +self.visit(node.operand) elif isinstance(node.op, ast.USub): return -self.visit(node.operand) else: raise SyntaxError("Unknown unary op: %r" % node.op)
Example #22
Source File: pytables.py From predictive-maintenance-using-machine-learning with Apache License 2.0 | 5 votes |
def visit_UnaryOp(self, node, **kwargs): if isinstance(node.op, (ast.Not, ast.Invert)): return UnaryOp('~', self.visit(node.operand)) elif isinstance(node.op, ast.USub): return self.const_type(-self.visit(node.operand).value, self.env) elif isinstance(node.op, ast.UAdd): raise NotImplementedError('Unary addition not supported')
Example #23
Source File: transpiler.py From pyrs with MIT License | 5 votes |
def visit_UnaryOp(self, node): if isinstance(node.op, ast.USub): if isinstance(node.operand, (ast.Call, ast.Num)): # Shortcut if parenthesis are not needed return "-{0}".format(self.visit(node.operand)) else: return "-({0})".format(self.visit(node.operand)) else: return super(RustTranspiler, self).visit_UnaryOp(node)
Example #24
Source File: compiler.py From Transcrypt with Apache License 2.0 | 5 votes |
def visit_UnaryOp (self, node): if self.allowOperatorOverloading and type (node.op) == ast.USub: self.emit ('{} ('.format (self.filterId ('__neg__' ))) self.visit (node.operand) self.emit (')') else: self.emit (self.operators [type (node.op)][0]) self.emitBeginTruthy () self.visitSubExpr (node, node.operand) self.emitEndTruthy ()
Example #25
Source File: utils.py From coffeegrindsize with MIT License | 5 votes |
def visitUnaryOp(self, node): import ast if isinstance(node.op, ast.UAdd): return +self.visit(node.operand) elif isinstance(node.op, ast.USub): return -self.visit(node.operand) else: raise SyntaxError("Unknown unary op: %r" % node.op)
Example #26
Source File: utils.py From Carnets with BSD 3-Clause "New" or "Revised" License | 5 votes |
def visitUnaryOp(self, node): import ast if isinstance(node.op, ast.UAdd): return +self.visit(node.operand) elif isinstance(node.op, ast.USub): return -self.visit(node.operand) else: raise SyntaxError("Unknown unary op: %r" % node.op)
Example #27
Source File: operators.py From wemake-python-styleguide with MIT License | 5 votes |
def _check_negation(self, op: ast.operator, right: ast.AST) -> None: is_double_minus = ( isinstance(op, (ast.Add, ast.Sub)) and isinstance(right, ast.UnaryOp) and isinstance(right.op, ast.USub) ) if is_double_minus: self.add_violation( consistency.OperationSignNegationViolation(right), )
Example #28
Source File: safe_eval.py From wemake-python-styleguide with MIT License | 5 votes |
def _convert_signed_num(node: Optional[ast.AST]): unary_operators = (ast.UAdd, ast.USub) if isinstance(node, ast.UnaryOp) and isinstance(node.op, unary_operators): operand = _convert_num(node.operand) return +operand if isinstance(node.op, ast.UAdd) else -operand return _convert_num(node)
Example #29
Source File: utils.py From Serverless-Deep-Learning-with-TensorFlow-and-AWS-Lambda with MIT License | 5 votes |
def visitUnaryOp(self, node): import ast if isinstance(node.op, ast.UAdd): return +self.visit(node.operand) elif isinstance(node.op, ast.USub): return -self.visit(node.operand) else: raise SyntaxError("Unknown unary op: %r" % node.op)
Example #30
Source File: utils.py From twitter-stock-recommendation with MIT License | 5 votes |
def visitUnaryOp(self, node): import ast if isinstance(node.op, ast.UAdd): return +self.visit(node.operand) elif isinstance(node.op, ast.USub): return -self.visit(node.operand) else: raise SyntaxError("Unknown unary op: %r" % node.op)