1

Is it possible to somehow cast a string of, say, or or and into a form that is recognizable as a logical operator?

For example, is it possible to do something like this:

l = [1, 2, 3, 4, 5]
o = {item1:'or'}

for i in l:
    if i > 4 o[item1] i < 0:
        print i

where o[item1] is recognized as a valid or logical operator?

5
  • It is possible to create an equivalent equivalent (fsvo) expression, but it is not possible to use it like that - which is merely invalid syntax - and the expression itself needs to be altered. Commented Sep 10, 2014 at 20:08
  • XY problem: why do you think you need this? Commented Sep 10, 2014 at 20:18
  • With some trickery you could get an (i > 4) |o[item1]| (i < 0) syntax to work (without short-circuiting) but you'd never use that in any real code so it's not much more than a parlour trick. Is there a particular problem you think this would help with? Maybe there's a better way to solve it. Commented Sep 10, 2014 at 20:20
  • I'm trying to solve the question I posted here: stackoverflow.com/questions/25691990/… Commented Sep 10, 2014 at 20:23
  • @DSM: and you could actually use a lot of different delimiters, like a <o[x]> b or a **o[x]** b or even a %o[x]% b...the possibilities are endless! :P Commented Sep 10, 2014 at 20:23

1 Answer 1

5

You may use the operator package:

import operator

o = {item1: operator.or_}

if o[item1](i>4, i<0):
    ...

Note that or_ does not short-circuit, like or does. If you really need the short-circuit behaviour, you can use eval (but this is in general not recommended).

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.