5

isinstance can be used to check if the object which is the first argument is an instance or subclass of classinfo class which is the second argument.

a = 1
b = [1]
isinstance(a,list)
isinstance(b,list)

Is there a similar way to check if an operator validate in Python? Something like

isoperator('=')
isoperator(':=')
isoperator('<-')

I am trying to build an online executor for Python very beginner.

When they input like this

enter image description here

they would get a hint, the operator is not supported rather than current error message.

2
  • 2
    Not if you use the syntactic sugar operators (i.e. the symbols +, -, =, etc), but you could use the equivalent function of an operator and have more control docs.python.org/3/library/operator.html Jul 7, 2019 at 3:28
  • 1
    How are you expecting to make use of this ability? A program containing invalid operators isn't going to run at all, it will fail to compile due to a SyntaxError. Jul 7, 2019 at 3:38

2 Answers 2

2

This can be achieved by wrapping a custom function around python's built in operator module. Of note, the operator can be inputted as a string or a lambda – I chose string arbitrarily.

import operator
import re
def test_operator(obj = [6], op_in = '> 1'):
  """
  returns true if operator can be performed, else false
  """
  # Use regex to parse the pattern
  pattern_funct = re.compile('[><=]+')
  pattern_num = re.compile('[0-9]+')
  # Access values
  funct = ''.join(pattern_funct.findall(op_in))
  num = float(''.join(pattern_num.findall(op_in)))

  # Lookup the operator function
  ops = {
      ">": operator.gt,
      ">=": operator.ge,
      "<": operator.lt,
      "<=": operator.le,
      "=": operator.eq,
  }   
  op_func = ops[funct]
  # Try to perform
  print(f'Trying `{obj}` with {op_in}:')
  try:
    op_func(obj, num)
    return True
  except  TypeError:
    return False


# Next!
x =[3]
print(test_operator(x,'>= 7 '), '\n' )
# False
print(test_operator(7,'>= 7 '))
# True
5
  • thanks for your answer. test_operator(x,'= 7 ') gets KeyError -------------------------------------------------------------------------- KeyError Traceback (most recent call last) <ipython-input-4-4bdaa477428f> in <module> ----> 1 test_operator(x,'= 7 ') <ipython-input-1-55fcce233737> in test_operator(obj, op_in) 19 "<=": operator.le 20 } ---> 21 op_func = ops[funct] 22 # Try to perform 23 print(f'Trying `{obj}` with {op_in}:') KeyError: '='
    – user10253483
    Jul 7, 2019 at 7:25
  • Let's add that to the keys... '=':operator.eq, Jul 7, 2019 at 14:27
  • Added, try again. Jul 7, 2019 at 14:28
  • my fault. by saying '=', I was meaning assignment, which is actually not a operator.
    – user10253483
    Jul 8, 2019 at 3:45
  • Is what you're trying to accomplish executable in another language? Also, thanks for accepting my answer. Jul 8, 2019 at 5:14
-1

.isalpha() return True if the character is like "hello" else return False then the character is like "+". so: "+".isalpha() return False
"hi".isalpha() retuen True

def isOperand(ch):
     return ch.isalpha()
 

def isOperator(ch):
     return True if ch.isalpha==False
1
  • This answer doesn't include non-numeric types and other possible strings that are not operators. Aug 11, 2021 at 19:59

Your Answer

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