473,748 Members | 3,697 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Introspection: expression evaluation order - precedence

Hi all,

this post contains at the end a handy module that I've used quite often
when I wanted to analyse the occasional complex expression and how it
was to be evaluated.

The function analyse_express ion is called with a single string argument
containing an expression. Names are allowed (actually, preferred over
numbers ;-), since the function eval's in a protected dictionary, where
names are generated as needed.
The output is a string containing many lines, where each line is of the
format:

[<operand1><spac e>]<operator><spac e><operand2>

<operand1> and 1st <space> are missing for unary operators.

There are only a few exception checks, since basically the function is
to be called with expressions pasted from actual syntactically correct
code.

Hope this helps other people, esp. newcomers in the python world.
Next step will be an tree-structured expression editor, allowing easy
editing (eg exchange the first argument of a function with the second
onei, even if these are complex expressions themselves, for people who
don't break down complex expressions as much as the Python spirit would
suggest), which could find a use inside Idle if done OK; but that will
be RSN :)
In case you find any flaws in this module, I would be glad to know and
correct them. Improvements are accepted without any arguments!

Examples:
print analyse_express ion('x+y-sqrt(5/-z.real*6)') x + y
z . real
- z.real
5 / -z.real
5/-z.real * 6
sqrt ( 5/-z.real*6 )
x+y - sqrt(5/-z.real*6)

Why names are preferred over numbers (a bug, actually ;-):
print analyse_express ion('5+sin(angl e=.6*x)')
Traceback (most recent call last):
File "<pyshell#1 6>", line 1, in -toplevel-
print analyse_express ion('5+sin(angl e=.6)')
File "analexpr.p y", line 68, in analyse_express ion
eval(code_objec t, namespace)
File "<evaluator >", line 0, in -toplevel-
TypeError: unsupported operand type(s) for +: 'int' and 'str'

but, substituting z for 5
print analyse_express ion('z+sin(angl e=.6*x)') 0.6 * x
sin ( angle=0.6*x )
z + sin(angle=0.6*x )

Don't use expressions without any names in it:
analyse_express ion('6+7-8*4') ''

cause it doesn't work... use at least one name:
print analyse_express ion('6+7-z*4') z * 4
13 - z*4

Using 'and', 'or' keywords will always behave as if their first operand
was True:
print analexpr.analys e_expression('z +7 and x+1 or y')

z + 7
x + 1
The module (no copyrights, public domain):

class EvaluationObjec t(object):
"""A helper class for analysing expressions"""
__slots__ = "_datum",
def __init__(self, datum):
self._datum = datum
def __str__(self):
return self._datum
def __call__(self, *args, **kwargs):
reply= []
reply.append(se lf._datum)
reply.append("( ")
if args:
out_arg_list1= []
for arg in args:
out_arg_list1.a ppend(str(arg). replace(' ', ''))
reply.append(', '.join(out_arg_ list1))
if kwargs:
out_arg_list2= []
for arg, value in kwargs.iteritem s():
out_arg_list2.a ppend("%s=%s" % (arg, value))
reply.append(', '.join(out_arg_ list2).replace( ' ', ''))
reply.append(") ")
rc = " ".join(repl y)
EvaluationObjec t.order.append( rc)
return rc

# create all the (EvaluationObje ct.__method__)s
def _make_binary_me thod(operator, reverse=False):
"Binary arithmetic operator factory function for EvaluationObjec t"
def _dummy(self, other):
if reverse: self, other = other, self
rc = "%s %s %s" % (str(self).repl ace(' ',''), operator,
str(other).repl ace(' ',''))
EvaluationObjec t.order.append( rc)
return EvaluationObjec t(rc)
return _dummy
# mass-make the arithmetic methods
for function in "add,+ sub,- mul,* floordiv,// mod,%" \
" pow,** lshift,<< rshift,>>" \
" and,& xor,^ or,| div,/ truediv,/" \
" getattr,.".spli t():
name, operator= function.split( ",")
setattr(Evaluat ionObject, "__%s__" % name,
_make_binary_me thod(operator))
setattr(Evaluat ionObject, "__r%s__" % name,
_make_binary_me thod(operator, reverse=True))

def _make_unary_met hod(operator):
"Unary arithmetic operator factory function for EvaluationObjec t"
def _dummy(self):
rc = "%s %s" % (operator, str(self).repla ce(' ', ''))
EvaluationObjec t.order.append( rc)
return EvaluationObjec t(rc)
return _dummy
for function in "neg,- pos,+ invert,~".split ():
name, operator = function.split( ",")
setattr(Evaluat ionObject, "__%s__" % name,
_make_unary_met hod(operator))

# cleanup
del _make_binary_me thod, _make_unary_met hod, function, name, operator

def analyse_express ion(expr):
'''Return as string a list of the steps taken to evaluate expr'''
code_object = compile(expr, "<evaluator >", "eval")
namespace = {'__builtins__' : {}}
# namespace should be a dict subclass that creates items
# on demand.
# exec and eval assume that the namespaces are dict objects
# and bypass any __getitem__ methods of the subclass
# to overcome this limitation, keep trying to eval the expression
# until no more name errors occur.
while True:
try:
EvaluationObjec t.order = []
eval(code_objec t, namespace)
except NameError, exc:
# exc.args[0] is of the form:
# name 'x' is not defined
# use hardcoded slice to get the missing name
name = exc.args[0][6:-16]
namespace[name] = EvaluationObjec t(name)
else:
break
result = '\n'.join(Evalu ationObject.ord er)
del EvaluationObjec t.order
return result

--
TZOTZIOY, I speak England very best,
Ils sont fous ces Redmontains! --Harddix
Jul 18 '05 #1
0 1731

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

70
8881
by: Roy Yao | last post by:
Does it mean "(sizeof(int))* (p)" or "sizeof( (int)(*p) )" ? According to my analysis, operator sizeof, (type) and * have the same precedence, and they combine from right to left. Then this expression should equal to "sizeof( (int)(*p) )", but the compiler does NOT think so. Why? Can anyone help me? Thanks. Best regards. Roy
2
2056
by: Jan Engelhardt | last post by:
Hi, I was told that order of evaluation is unspecified for functions, i.e. int f = 0; print_results(modify(&f), modify(&f), modify(&f)); where i.e. modify() increases f by one. In my case w/gcc, it was evaluated from right-to-left (gcc does a nice stack optimization). Not what I expected though.
8
1608
by: manan.kathuria | last post by:
hi all , the expression in question is ++i&&++j||++k most sources say that since the result of the || operation is decided by the LHS itself , the right side is not computed my point of thinking is that since the unary operator has higher precedence than || , it will be evaluated before || in any
32
3318
by: silpau | last post by:
hi, i am a bit confused on expression evaluation order in expressions involving unary increment.decrement operators along with binary operators. For example in the following expression x += i + j + k++;
54
3939
by: Rasjid | last post by:
Hello, I have just joined and this is my first post. I have never been able to resolve the issue of order of evaluation in C/C++ and the related issue of precedence of operators, use of parentheses. 1) "The order of evaluation of subexpressions is determined by the precedence and grouping of operators."
0
8828
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
9537
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
9319
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9243
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
8241
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
4599
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
4869
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3309
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
3
2213
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.