i have conditions/comparisons stored strings. how can check these conditions? simple example given below. want conditions strings because want print them in case fail.
i think i'll need make parser stupid idea make complete python parser small thing. ideas can done?
def rev_num(num): if num < 0: return -int(str(-num)[::-1]) else: return int(str(num)[::-1]) conditions = ['rev_num(-34) != -43', 'rev_num(34) != 43'] in conditions: if something-needs-to-come-here(i): print(i) i know weird idea please tag along if can.
i caused confusion user2357112. pointed out trying called unit-testing. that.
to avoid further confusion i'll add code trying improve. change want make print condition in function correctness made return false.
def rev_num(num): if num < 0: return -int(str(-num)[::-1]) else: return int(str(num)[::-1]) if __name__ == "__main__": timeit import timer import random def correctness(f): print("correctness test") if f(-34) != -43 or f(34) != 43: return false print('correct') print('-----------') return true def timing(f, times): def test1(f): f(random.randint(1, 1000)) def test2(f): f(random.randint(100000, 1000000)) print("timing test") print(timer(lambda: test1(f)).timeit(number = times)) print(timer(lambda: test2(f)).timeit(number = times)) print('-----------') def tests(f,times): print(f.__name__) print('-----------') if correctness(f) true: timing(f, times) repeat = 100000 tests(rev_num, repeat)
you can using eval(cond_string):
for in conditions: if eval(i): print(i) edit: yes, several have pointed out, eval can dangerous if can't absolutely content of strings you're evaluating. reason, using eval seen bad general practice, though may simplest way achieve you're aiming here.
if purpose perform sanity checks code maintenance purposes, take @ unittest module.
Comments
Post a Comment