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

Forum statistics

Threads
473,981
Messages
2,570,188
Members
46,731
Latest member
MarcyGipso

Latest Threads

Top