How to program test(expr) ?

Ulrich Eckhardt ulrich.eckhardt at dominolaser.com
Thu Aug 30 03:33:58 EDT 2012


Am 29.08.2012 17:04, schrieb Franck Ditter:
> I use Python 3.2.3 + Idle.
> Is it possible to program test(e) which takes
> an expression e and whose execution produces
> at the toplevel an echo of e and the effects
> and result of its evaluation ?

Yes, the key to this is using a lambda expression.


> # file foo.py
> def foo(x) :
>    print('x =',x)
>    return x+1
>
> test(foo(5))

def test(exp):
     global print
     print_saved = print
     print = my_print
     res = exp()
     print = print_saved
     return res

test(lambda: foo(5))


The idea is to run the callable expression inside a modified 
environment, in the sketch above it intercepts the calles to print() 
using a separate my_print() function. Note that the calling syntax is 
slightly different than the one you would have wanted, don't know if 
that is important.

Things I'll leave to you:
  - exception handling
  - exception forwarding
  - intercepting other environment accesses
  - putting all that into a context manager :)


Good luck!


Uli





More information about the Python-list mailing list