开发者

Python parsing boolean expressions with custom evaluations

Hello Im working on a django project where i want to store a set of requirements for a course, but these requirements are not simple, they could be a combination of and / or ie,

((course1 or course2) and course3)

I found this boolean parser, and have kinda figured out how it works, the only hickup is开发者_如何学编程 that once it gets an operand, it uses eval() to find the value of the variable. In my case, these values will be dynamic and need to be calculated based on certain parameters. Any ideas on implementation would be greatly helpful.


You can create your own resolver for names like this:

class NameResolver(object):
    def __getitem__(self, key):
        return "dynamic %r" % key

>>> eval("foo, bar", {}, NameResolver())
("dynamic 'foo'", "dynamic 'bar'")

However, is the administrator of the site the one who configures these requirements? Using eval() will execute any code, so it is always a potential security risk. If the requirements come from an untrusted source, then building custom parser using the ast module would be a better solution.


Try using Python expressions and the eval() function:

>>> course1 = True
>>> course2 = False
>>> course3 = True
>>> print eval('(course1 or course2) and course3')
True

But if expressions can come from outside your app, you will have a security problem because folks could inject and execute arbitrary Python.

In that case, look at ast.literal_eval(). See: http://docs.python.org/library/ast.html#ast.literal_eval

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜