开发者

eagerly evaluating boolean expressions in Python

开发者 https://www.devze.com 2022-12-20 02:11 出处:网络
Is there a way (using eval or whatever) to evaluate eagerly boolean expressions in python? Let\'s see this:

Is there a way (using eval or whatever) to evaluate eagerly boolean expressions in python?

Let's see this:

>>> x = 3
>>> 5 < x < y
False

Yikes! That's very nice, because this will be false regardless of y's value. The thing is, y can be even undefined, and I'd like to get that exception. How can I get python to evaluate all expressions even if it knows 开发者_开发问答the result beforehand?

Hope I made myself clear! Thanks,

Manuel

Edit: Please bear in mind that the expression must not be modified, just the evaluation technique.


(5 < x) & (x < y)

By using the bit-and operator, &, you get no short-circuiting behavior (as you get with and, or, chaining, all/any). Short-circuiting is normally deemed desirable (fast &c) but it's not hard to do without it if you really want;-).


all([5 < x, x < y])


The most natural way would probably be to evaluate the expressions on prior lines.

a = foo()
b = bar()
if a and b:
    ...

as solutions like all([5 < x, x < y]) hide that the side effects are important and solutions using bitwise and (&) seem subtle and misusing—both of these would require a comment in your code to make it obvious you are forcing evaluation and will cause people reading your code to think What was he thinking???. Putting important calculations on their own lines makes more sense than hiding them within subtle, at-first-glance ugly code.

Though my solution doesn't prevent a NameError if b does not exist (i.e., you have a typo) and a is false, this is something you should be able to figure out by reading your code and using a bugfinder if you choose.


>>> x = 3
>>> y > x > 5
Traceback (most recent call last):
  File "", line 1, in 
NameError: name 'y' is not defined


If it's just the possibility of programmer-error you want to preclude, eagerly evaluating expressions won't do much. For instance, mistakenly doing x or y() instead of x() or y() won't be detected. Perhaps you're actually looking for tools like pylint, pyflakes or pychecker.


If you are receiving the statement from the user and want to execute it with your own semantics, you should parse it yourself with a tool such as pyparsing. It is messy and insecure to evaluate someone else's code in the middle of yours, mixing their results with yours and it is confusing to evaluate what looks to be Python code but with different semantics.

0

精彩评论

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