dictionary of operators
rbossy at jouy.inra.fr
rbossy at jouy.inra.fr
Thu Feb 14 10:49:37 EST 2008
Hi,
In the standard library module "operator", it would be nice to have a dictionary
mapping operators strings with their respective functions. Something like:
{
'+': add,
'-': sub,
'in': contains,
'and': and_,
'or': or_,
...
}
Rationale:
Recently I had to implement a small language interpreter and I ended up building
such a dictionary. Indeed the parser (I used PLY then pybison) returned an AST,
where all arithmetic were represented by a single node type, like this:
class Arithmetic(Expression):
def __init__(self, op, lft, rgt):
self.op = op
self.lft = lft
self.rgt = rgt
def eval(self, scope):
return self.op(self.lft.eval(scope), self.rgt.eval(scope))
The dictionary allowed the parser to have a single rule action like this:
Arithmetic(opstr[term[1]], term[0], term[2])
Does such a dictionary already exist? Is it really a good and useful idea?
Thanks,
RB
More information about the Python-list
mailing list