Using an operator as an object

Alex Martelli aleax at aleax.it
Mon Mar 3 09:02:35 EST 2003


Cameron Laird wrote:

> In article <b3v7ha01gvg at enews3.newsguy.com>,
> Alex Martelli  <aleax at aleax.it> wrote:
> .
>>Python library.  However, if you DO have a string representing
>>an operator, an if/elif tree is still not the best way to find
>>out which one of the functions in module operator you have to
>>call -- rather, you're probably better off building a dictionary
>>once only:
>>
>>import operator
>>string_to_op = {
>>    '+': operator.add,
>>    '-': operator.sub,
>>    '*': operator.mul,
>>    '/': operator.div,
>>    '%': operator.mod,
>>    # and possibly others if you need them, of course
>>}
> .
> Is such a mapping not already exposed somewhere?

Not to my knowledge, no.

> 'Near as I can tell, the answer is, "No".  Would
> this not be one of the benefits of the (several)
> project(s) to script more of Python's core in
> Python?

I guess it might.  Here's a first attempt to make such a
map, e.g. for operators with two operands:

import re

renametc = re.compile('(\w+).*ame as (.*)')
reoperan = re.compile('a *([^ ]+) *b')

import operator

print '{'
for name in dir(operator):
        doc = getattr(operator,name).__doc__
        mat = renametc.match(doc)
        if not mat or name != mat.group(1): continue
        opstring = mat.group(2)
        mat = reoperan.match(opstring)
        if not mat: continue
        print '  %r: operator.%s,' % (mat.group(1), name)
print '}'


which prints:

{
  '+': operator.add,
  '&': operator.and_,
  '+': operator.concat,
  '/': operator.div,
  '==': operator.eq,
  '//': operator.floordiv,
  '>=': operator.ge,
  '[': operator.getitem,
  '[': operator.getslice,
  '>': operator.gt,
  'is': operator.is_,
  '<=': operator.le,
  '<<': operator.lshift,
  '<': operator.lt,
  '%': operator.mod,
  '*': operator.mul,
  '!=': operator.ne,
  '|': operator.or_,
  '**': operator.pow,
  '>>': operator.rshift,
  '[': operator.setitem,
  '[': operator.setslice,
  '-': operator.sub,
  '/': operator.truediv,
  '^': operator.xor,
}

of course, this needs some cleanup (it has no way to find
out whether the "right" mapping e.g. for '+' is to be
operator.add or operator.concat, etc), but, it's a start.


Alex






More information about the Python-list mailing list