Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to implement multiple assignment in an interpreter written in python?

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.

like image 840
Saad Avatar asked Apr 10 '13 17:04

Saad


People also ask

How are multiple assignments made in Python?

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.

What is the purpose of multiple assignments in Python?

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.

How do you use simultaneous assignment in Python?

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.

How do assignments work in Python?

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.


1 Answers

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.

like image 130
Tobia Avatar answered Sep 19 '22 07:09

Tobia