[英]Look up operators programmatically by string name
Suppose I have the following code: 假设我有以下代码:
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. >=, <=, !=
How can I distill this down more programmatically? 我怎样才能以编程方式更好地提炼出来呢? I'm thinking of creating a lookup like this:
我正在考虑创建这样的查找:
op_lookup = {'eq': '==', 'gt': '>', 'lt': '<', ...}
Then doing something like this: 然后做这样的事情:
def process(x, y, op):
return x op_lookup[op] y
Which obviously isn't valid Python... 哪个显然不是有效的Python ...
Something like eval
might work: 像
eval
这样的东西可能会起作用:
def process(x, y, op):
return eval('{} {} {}'.format(x, op_lookup[op], y))
Which produces this, in an example: 在一个例子中产生这个:
>>> process(1, 1, 'eq')
True
>>> process(1, 1, 'lt')
False
Is there a better (safer?) way of accomplishing this? 是否有更好(更安全?)的方式来实现这一目标?
Operators as callables are hidden in the operator
module. 作为可调用的
operator
隐藏在operator
模块中。 You can dynamically access a specific operator by its name with the getattr
builtin. 您可以使用
getattr
内置函数以名称动态访问特定运算符。
Demo: 演示:
>>> 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
We can use this to rewrite your function as follows. 我们可以使用它来重写您的函数,如下所示。
import operator
def process(x, y, op):
return getattr(operator, op)(x, y)
(Add sanity checks as required.) (根据需要添加健全性检查。)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.