How to program test(expr) ?

F

Franck Ditter

Hi !
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 ?

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

test(foo(5))

# RUN !

# produces at the toplevel :
? foo(5)
x = 5
--> 6

I know I could put the expression e within a string, but
is it possible to avoid the string, like a Lisp macro ?

Thanks.

franck
 
T

Terry Reedy

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 ?

No, not as Python is delivered.
# file foo.py
def foo(x) :
print('x =',x)
return x+1

test(foo(5))

# RUN !

# produces at the toplevel :
? foo(5)
x = 5
--> 6

I know I could put the expression e within a string, but
is it possible to avoid the string, like a Lisp macro ?

It might be possible to write an IDLE extension that would 'process'
interactive input looking for (untested) re pattern something like
'test\((.*)\)'. Given a match, it prints the captured .* part and passes
it on to the Python interpreter, and prefixes output with '-->'.
(I have not yet looked at how to write extensions.)
 
U

Ulrich Eckhardt

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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,011
Latest member
AjaUqq1950

Latest Threads

Top