Late code evaluation and also printing the code

54 Views Asked by At

I want to pass code to a test() routine, which has to :

  1. print the code
  2. execute it
  3. and finally do stuff with the result.
  4. should handle args in the background

For quick code snippets I can use eval(code-string), like this:

def test_eval(expr_str, expected):
    global a,b
    res = eval(expr_str) == expected
    print(f'{res} : {expr_str}')

but for:

  • code with assignment
  • test() should do argumentless calling of fun(), even for fun(a, b...)
  • or longer code

the approach is unusable.


SOLVED

def test(fun,expected,args):
    res = fun(*args) == expected
    expr = inspect.getsource(fun)
    print(f'{res} : {expr}')


def tests():fun()
    def w(a,b):#args
        a += b #assignment
        return a.sym == "(a + b)"

    a = ...
    b = ...
    test(w,True,(a,b))

better ideas?

0

There are 0 best solutions below