Is it possible to check if a variable fulfills logical expression stored as a string?

Viewed 55

If I have a variable

dummy = 'abc'

And a dictionary where I keep different logical OR expressions where OR is represented by |.

logic_dict = {'1':'def|how', '2':'does|this', '3':'abc|hi'}

I would want to compare the logical expressions against the fixed variable in some way, the following for loop does not work, but it shows how I would ideally want to do it.

for test_number,logic_string in logic_dict.items():
    print(dummy == logic_string)

Which I would want to output

False
False
True

I know that I can do this manually by writing

print(dummy == 'def' or dummy == 'how')
print(dummy == 'does' or dummy == 'this')
print(dummy == 'abc' or dummy =='hi')

But Is there a way to do this with the string representation of the logical expression?

1 Answers

I'm not really sure how you set yourself up for this situation, and I'm pretty sure there's a way to properly avoid such convoluted logical clause parsing, but for what it's worth, here's how you can deal with the specific use-case at hand:

dummy = 'abc'
logic_dict = {'1':'def|how', '2':'does|this', '3':'abc|hi'}

for test_number,logic_string in logic_dict.items():
    print(dummy in logic_string.split('|'))

Note of warning: This whole concept goes haywire (and the suggested solution is appropriately worthless) if your string includes a | character...

Related