按字符串名称以编程方式查找运算符

Look up operators programmatically by string name

假设我有以下代码:

def process(x, y, op):
    if op == 'eq':
        return x == y
    elif op == 'gt':
        return x > y
    elif op == 'lt':
        return x < y
    ... for many more operators, e.g. >=, <=, !=

我怎样才能以更编程的方式提炼出来?我正在考虑创建这样的查找:

op_lookup = {'eq': '==', 'gt': '>', 'lt': '<', ...}

然后做这样的事情:

def process(x, y, op):
    return x op_lookup[op] y

显然 无效 Python...

类似 eval 的方法可能有效:

def process(x, y, op):
    return eval('{} {} {}'.format(x, op_lookup[op], y))

产生这个,在一个例子中:

>>> process(1, 1, 'eq')
True
>>> process(1, 1, 'lt')
False

是否有更好(更安全?)的方法来完成此操作?

operator模块就是你想要的:

>>> import operator
>>> op_lookup = {'eq': operator.eq, 'gt': operator.gt, 'lt': operator.lt}
>>> 
>>> def process(x, y, op):
...     return op_lookup[op](x, y)
... 
>>> process(1, 1, 'eq')
True
>>> process(1, 1, 'lt')
False

运算符作为可调用项隐藏在 operator module. You can dynamically access a specific operator by its name with the getattr 内置函数中。

演示:

>>> import operator         
>>> getattr(operator, 'eq')(1, 1)
True
>>> getattr(operator, 'eq')(1, 2)
False
>>> getattr(operator, 'lt')(1, 2)
True
>>> getattr(operator, 'lt')(2, 1)
False

我们可以使用它来重写您的函数,如下所示。

import operator

def process(x, y, op):
    return getattr(operator, op)(x, y)

(根据需要添加完整性检查。)