1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41
| from operator import lt, le, eq, ne, gt, ge
class Testeur:
OPERATOR = {
'<': lt, '<=': le, '>': gt,
'>=': ge, '==': eq, '!=': ne
}
ERRORS = {
'operate': 'separate by space your expression',
'key': '{} operator is not valid (<, <=, >, >=, ==)'
}
def __init__(self, condition):
'''condition with this form a < b'''
self.condition = condition
self.parse()
def parse(self):
try:
self.var, self.op, self.value = self.condition.split()
except ValueError:
raise ValueError(self.ERRORS['operate'])
def tester(self):
try:
oper = self.OPERATOR[self.op]
except KeyError:
raise ValueError(self.ERRORS['key'])
return oper(globals()[self.var], int(self.value))
a = 5
t = Testeur('a == 5')
print(t.tester()) # True
t = Testeur('a > 2')
print(t.tester()) # True
t = Testeur('a <= 2')
print(t.tester()) # False |
Partager