lmfit / asteval

minimalistic evaluator of python expression using ast module
https://lmfit.github.io/asteval
MIT License
183 stars 41 forks source link

Variable unpacking does not work as expected #126

Closed elmer-le-ai closed 5 months ago

elmer-le-ai commented 7 months ago

I have the following output with 0.9.32:

>>> import asteval
>>> ev = asteval.Interpreter()
>>> ev('[(x,y) for (x,y) in [(1,2), (3,4)]]') 
[(1, 2), (1, 4), (3, 2), (3, 4)]
>>> [(x,y) for (x,y) in [(1,2), (3,4)]] # actual python output
[(1, 2), (3, 4)]

It seems like unpacking in asteval is taking the cartesian product of x and y.

newville commented 7 months ago

@elmer-le Thanks -- that's bad! I think it will be fixable, but I am not certain when I'll get to this.

chrisjbremner commented 5 months ago

I just ran into the same issue and tracked it down to being introduced in 0.9.28. Here's another reproduction:

import asteval
a=asteval.Interpreter()
data={'1': 123, '2': 456, '3': 789}
a.symtable['data']=data
print(a("multiplier = {'1': 3, '2': 2, '3': 1};sum([v*multiplier[k] for k, v in data.items()])")) # Returns 8208
multiplier = {'1': 3, '2': 2, '3': 1}
print(sum([v*multiplier[k] for k, v in data.items()])) # Returns 2070
newville commented 5 months ago

@elmer-le @chrisjbremner These are now fixed in the master branch.

chrisjbremner commented 5 months ago

Thanks! Confirmed it worked for my use case. Looking forward to the next release so I can incorporate it!

newville commented 5 months ago

@chrisjbremner Thanks - I'll close this.

chrisjbremner commented 5 months ago

Thanks, do you anticipate a release soon that incorporates this change?

newville commented 5 months ago

@chrisjbremner Yes, that is on my list, hopefully by the end of the week.

newville commented 5 months ago

@chrisjbremner 0.9.33 is now released and pushed to PyPI.