我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用parser.expr()。
def decorator(self, nodelist): # '@' dotted_name [ '(' [arglist] ')' ] assert len(nodelist) in (3, 5, 6) assert nodelist[0][0] == token.AT assert nodelist[-1][0] == token.NEWLINE assert nodelist[1][0] == symbol.dotted_name funcname = self.decorator_name(nodelist[1][1:]) if len(nodelist) > 3: assert nodelist[2][0] == token.LPAR expr = self.com_call_function(funcname, nodelist[3]) else: expr = funcname return expr
def __new__(cls, name, expr, replace = False): # code efound = expr in [Variable.variables[key].expr for key in Variable.variables] if efound: key = [key for key in Variable.variables if expr in Variable.variables[key].expr] logger.info("Expression '%s' already exists for key %s", expr, key) return else: if replace or not name in Variable.variables: if not valid_name(name): logger.info("Invalid variable key: %s", name) return try: result = parser.expr(expr) except: logger.info("Invalid expression: %s", expr) return return super(Variable, cls).__new__(cls) else: logger.info("Key %s already exists", name) # function __init__
def __contains__(self, expr): """Implement membership test operator. Return true if expr matches a packet in the trace file, false otherwise. The packet is also stored in the object attribute pkt. Examples: # Find the next READ request if ("NFS.argop == 25" in x): print x.pkt.nfs See match() method for more information """ pkt = self.match(expr) return (pkt is not None)
def _match(self, layer, uargs): """Default match function.""" if not hasattr(self.pkt, layer): return False if layer == "nfs": # Use special matching function for NFS texpr = self.match_nfs(uargs) else: # Use general match obj = "self.pkt.%s." % layer.lower() lhs, opr, rhs = self._split_match(uargs) expr = self._process_match(obj, lhs, opr, rhs) texpr = eval(expr) self.dprint('PKT2', " %d: match_%s(%s) -> %r" % (self.pkt.record.index, layer, uargs, texpr)) return texpr
def evaluate_marker(cls, text, extra=None): """ Evaluate a PEP 426 environment marker on CPython 2.4+. Return a boolean indicating the marker result in this environment. Raise SyntaxError if marker is invalid. This implementation uses the 'parser' module, which is not implemented on Jython and has been superseded by the 'ast' module in Python 2.6 and later. """ return cls.interpret(parser.expr(text).totuple(1)[1])
def parseexpr(self, text): """Return a modified parse tree for the given expression text.""" return self.transform(parser.expr(text))
def yield_stmt(self, nodelist): expr = self.com_node(nodelist[0]) return Discard(expr, lineno=expr.lineno)
def exec_stmt(self, nodelist): # exec_stmt: 'exec' expr ['in' expr [',' expr]] expr1 = self.com_node(nodelist[1]) if len(nodelist) >= 4: expr2 = self.com_node(nodelist[3]) if len(nodelist) >= 6: expr3 = self.com_node(nodelist[5]) else: expr3 = None else: expr2 = expr3 = None return Exec(expr1, expr2, expr3, lineno=nodelist[0][2])
def comparison(self, nodelist): # comparison: expr (comp_op expr)* node = self.com_node(nodelist[0]) if len(nodelist) == 1: return node results = [] for i in range(2, len(nodelist), 2): nl = nodelist[i-1] # comp_op: '<' | '>' | '=' | '>=' | '<=' | '<>' | '!=' | '==' # | 'in' | 'not' 'in' | 'is' | 'is' 'not' n = nl[1] if n[0] == token.NAME: type = n[1] if len(nl) == 3: if type == 'not': type = 'not in' else: type = 'is not' else: type = _cmp_types[n[0]] lineno = nl[1][2] results.append((type, self.com_node(nodelist[i]))) # we need a special "compare" node so that we can distinguish # 3 < x < 5 from (3 < x) < 5 # the two have very different semantics and results (note that the # latter form is always true) return Compare(node, results, lineno=lineno)
def expr(self, nodelist): # xor_expr ('|' xor_expr)* return self.com_binary(Bitor, nodelist)
def com_try_except_finally(self, nodelist): # ('try' ':' suite # ((except_clause ':' suite)+ ['else' ':' suite] ['finally' ':' suite] # | 'finally' ':' suite)) if nodelist[3][0] == token.NAME: # first clause is a finally clause: only try-finally return TryFinally(self.com_node(nodelist[2]), self.com_node(nodelist[5]), lineno=nodelist[0][2]) #tryexcept: [TryNode, [except_clauses], elseNode)] clauses = [] elseNode = None finallyNode = None for i in range(3, len(nodelist), 3): node = nodelist[i] if node[0] == symbol.except_clause: # except_clause: 'except' [expr [(',' | 'as') expr]] */ if len(node) > 2: expr1 = self.com_node(node[2]) if len(node) > 4: expr2 = self.com_assign(node[4], OP_ASSIGN) else: expr2 = None else: expr1 = expr2 = None clauses.append((expr1, expr2, self.com_node(nodelist[i+2]))) if node[0] == token.NAME: if node[1] == 'else': elseNode = self.com_node(nodelist[i+2]) elif node[1] == 'finally': finallyNode = self.com_node(nodelist[i+2]) try_except = TryExcept(self.com_node(nodelist[2]), clauses, elseNode, lineno=nodelist[0][2]) if finallyNode: return TryFinally(try_except, finallyNode, lineno=nodelist[0][2]) else: return try_except
def com_with_item(self, nodelist, body, lineno): # with_item: test ['as' expr] if len(nodelist) == 4: var = self.com_assign(nodelist[3], OP_ASSIGN) else: var = None expr = self.com_node(nodelist[1]) return With(expr, var, body, lineno=lineno)
def com_list_comprehension(self, expr, node): return self.com_comprehension(expr, None, node, 'list')
def com_dictorsetmaker(self, nodelist): # dictorsetmaker: ( (test ':' test (comp_for | (',' test ':' test)* [','])) | # (test (comp_for | (',' test)* [','])) ) assert nodelist[0] == symbol.dictorsetmaker nodelist = nodelist[1:] if len(nodelist) == 1 or nodelist[1][0] == token.COMMA: # set literal items = [] for i in range(0, len(nodelist), 2): items.append(self.com_node(nodelist[i])) return Set(items, lineno=items[0].lineno) elif nodelist[1][0] == symbol.comp_for: # set comprehension expr = self.com_node(nodelist[0]) return self.com_comprehension(expr, None, nodelist[1], 'set') elif len(nodelist) > 3 and nodelist[3][0] == symbol.comp_for: # dict comprehension assert nodelist[1][0] == token.COLON key = self.com_node(nodelist[0]) value = self.com_node(nodelist[2]) return self.com_comprehension(key, value, nodelist[3], 'dict') else: # dict literal items = [] for i in range(0, len(nodelist), 4): items.append((self.com_node(nodelist[i]), self.com_node(nodelist[i+2]))) return Dict(items, lineno=items[0][0].lineno)
def __init__(self, name, expr, replace = False): # code self.name = name; self.expr = expr; # add key with expression Variable.variables[name] = self # function __str__
def __str__(self): return self.expr # # Function vparse #
def allvars(expr): r"""Get the list of valid names in the expression. Parameters ---------- expr : str A valid expression conforming to the Variable Definition Language. Returns ------- vlist : list List of valid variable names. """ regex = re.compile('\w+') items = regex.findall(expr) vlist = [] for item in items: if valid_name(item): vlist.append(item) return vlist # # Function vtree #
def has_unparsable_defaults(sig: inspect.Signature) -> bool: """Return whether or not the reprs for all defaults in the signature are valid python expressions""" for param in sig.parameters.values(): if param.default is inspect.Parameter.empty: continue try: parser.expr(repr(param.default)) except SyntaxError: return True return False
def check_expr(self, s): self.roundtrip(parser.expr, s)
def test_compile_expr(self): st = parser.expr('2 + 3') code = parser.compilest(st) self.assertEqual(eval(code), 5)
def test_issue_9011(self): # Issue 9011: compilation of an unary minus expression changed # the meaning of the ST, so that a second compilation produced # incorrect results. st = parser.expr('-3') code1 = parser.compilest(st) self.assertEqual(eval(code1), -3) code2 = parser.compilest(st) self.assertEqual(eval(code2), -3)
def test_deeply_nested_list(self): # XXX used to be 99 levels in 2.x e = self._nested_expression(93) st = parser.expr(e) st.compile()
def test_trigger_memory_error(self): e = self._nested_expression(100) print("Expecting 's_push: parser stack overflow' in next line", file=sys.stderr) sys.stderr.flush() self.assertRaises(MemoryError, parser.expr, e)
def test_deeply_nested_list(self): e = self._nested_expression(99) st = parser.expr(e) st.compile()
def test_sizeof(self): def XXXROUNDUP(n): if n <= 1: return n if n <= 128: return (n + 3) & ~3 return 1 << (n - 1).bit_length() basesize = support.calcobjsize('Pii') nodesize = struct.calcsize('hP3iP0h') def sizeofchildren(node): if node is None: return 0 res = 0 hasstr = len(node) > 1 and isinstance(node[-1], str) if hasstr: res += len(node[-1]) + 1 children = node[1:-1] if hasstr else node[1:] if children: res += XXXROUNDUP(len(children)) * nodesize for child in children: res += sizeofchildren(child) return res def check_st_sizeof(st): self.check_sizeof(st, basesize + nodesize + sizeofchildren(st.totuple())) check_st_sizeof(parser.expr('2 + 3')) check_st_sizeof(parser.expr('2 + 3 + 4')) check_st_sizeof(parser.suite('x = 2 + 3')) check_st_sizeof(parser.suite('')) check_st_sizeof(parser.suite('# -*- coding: utf-8 -*-')) check_st_sizeof(parser.expr('[' + '2,' * 1000 + ']')) # XXX tests for pickling and unpickling of ST objects should go here
def testlist(self, nodelist): # testlist: expr (',' expr)* [','] # testlist_safe: test [(',' test)+ [',']] # exprlist: expr (',' expr)* [','] return self.com_binary(Tuple, nodelist)