Replace variables during parsing - pyparsing

487 Views Asked by At

Suppose I have somewhat of a simplified expression as follows

(3 + 7 + (x + 5))

Is there a way using pyparsing that I can evaluate the expression and during the runtime notice x is a variable that needs to be replaced by the outer expression? So basically 3+7 gets evaluated to 10, x is a variable that gets replaced by 10 so the final expression would be

(3 + 7 + (10 + 5)) 

had I known x was 10 before runtime.

The variable will always have a 'parent' above it for replace. I'm really not sure where to start looking.

I guess my questions are:

  1. Does pyparsing allow for something like this?
  2. If not is there a parsing library in python that does?
  3. Am I better off building my own parser for this problem where I could implement a peek() or next() method to allow me handle this as I recurse

Any hints or documentation to get started would be great.

EDIT: Sorry if I lead people in the wrong direction or caused confusion my trying to oversimplify my question. I'll try to expand more but it get's complicated as there would be quite a bit of coding behind it.

Say I have the following dictionary:

prices_by_day = {
  'monday' : [
    {'name' : 'apple', 'price' : 0.99},
    {'name' : 'orange', 'price': 1.99}
  ],
  'tuesday': [
    {'name' : 'apple', 'price' : 0.50},
    {'name' : 'orange', 'price': 0.80}
  ]
}

What I want to be able to do is write an expression to get the price for apples on monday take that price and find all items that are less than that price for tuesday. The problem is that I won't always know the price of apples on monday or the price may change, but I want to be able to pass that down into an expression once I know for something like

 get(price of apples monday) and 
 get(price of all tuesday array objects < ${PREVIOUSLY_EVALUAED_PRICE_OF_APPLES})

I hope this helped explain more and didn't make it more confusing.

0

There are 0 best solutions below