I am writing an interpreter in python and I am following this example http://www.dabeaz.com/ply/example.html
I would like to know how I can implement multiple assignment such as:
a=b=c=1
and a=(b=1)*1
I have tried a few rules but all in vain. I know the parsing should be something like this.
a b c 1
\ \ \/
\ \ /
\ \ /
\ /
I am just not sure how to write this using PLY.
Multiple assignment in Python: Assign multiple values or the same value to multiple variables. In Python, use the = operator to assign values to variables. You can assign values to multiple variables on one line.
Multiple assignment (also known as tuple unpacking or iterable unpacking) allows you to assign multiple variables at the same time in one line of code. This feature often seems simple after you've learned about it, but it can be tricky to recall multiple assignment when you need it most.
This is called simultaneous assignment. Semantically, this tells Python to evaluate all the expressions on the right-hand side and then assign these values to the corresponding variables named on the left-hand side. Here's an example. Here sum would get the sum of x and y and diff would get the difference.
The assignment operator, denoted by the “=” symbol, is the operator that is used to assign values to variables in Python. The line x=1 takes the known value, 1, and assigns that value to the variable with name “x”. After executing this line, this number will be stored into this variable.
Most languages get away with it by declaring assignment to be an expression.
In your example, assignment becomes:
def p_expression_assign(t):
'expression : NAME EQUALS expression'
t[0] = names[t[1]] = t[3]
I just changed "statement" to "expression", both in the function name and in the docstring syntax, and "returned" (assigned to t[0]
) the value that is being assigned.
I say "get away with" because other languages (such as Python) go the extra mile, as they allow multiple assignments, but forbid using the result of the assignment in any other kind of expression.
But your second example a=(b=1)*1
tells me you want the former, more lax (or C-like) form of multiple assignment.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With