dict to boolean expression, how to?

Peter Otten __peter__ at web.de
Fri Aug 1 11:44:27 EDT 2014


Alex van der Spek wrote:


> I do know eval() lends itself to code injection but can't say I am
> fully aware of its dangers. It seemed like a handy tool to me.

In a lab if you don't need to protect your script against attacks from 
outside eval() (and exec()) is fine. If the data fed to eval() is completely 
under your control (think collections.namedtuple) eval() is also fine.

Adding a public web interface on such a lab application means trouble.

> This newsgroup scares me, 

If you dare say that you are not scared enough ;)

> it appears to be for professional computer
> scientists only, the theoretical part is sometimes too much for this
> practical physicist with an old background in FORTRAN.

That sounds like you are experienced enough to say "There may be problems 
with this code, but I choose not to care about them this time -- at my own 
risk"
 
> Is there a better place to ask questions of this nature?

There is the tutor mailing list which is mostly geared at absolute 
beginners, does more hand-holding, and the threads are more likely to stay 
on topic. You might take a look, but with your background you are probably 
better off here.

> I am sorry, the problem is ill posed.
> 
> 'a', 'A' and so forth are my failed attempt to shorthand.
> 
> In reality the dict's keys are column names in a pandas dataframe df.
> 
> The boolean expression would therefore look like:
> 
> bool = ((df['a'] == 1) & (df['A'] == 0) |
>          (df['b'] == 1) & (df['B'] == 0) |
>          (df['c'] == 1) & (df['C'] == 0))
 
This is how it might look without eval():

#untested
result = functools.reduce(operator.or_, ((v == 1) & (df[k.upper()] == 0) for 
k, v in df.items() if k.islower()))

And here is an eval-based solution:

# untested
expr = "|".join(
    "((df[{}] == 1) | (df[{}] == 0))".format(c, c.upper()) 
    for c in df is c.islower())
result = eval(expr)
-------------- next part --------------
A non-text attachment was scrubbed...
Name: konsole.desktop
Type: application/x-desktop
Size: 4773 bytes
Desc: not available
URL: <http://mail.python.org/pipermail/python-list/attachments/20140801/6fb37714/attachment.bin>


More information about the Python-list mailing list