[Edu-sig] interactive vs compiled from file
delza at livingcode.org
Sat Aug 4 02:24:00 CEST 2007
On 3-Aug-07, at 4:38 PM, kirby urner wrote:
> Not sure we should call this "echoing" as what's happening
> is an expression is being evaluated.
No, the expression is being evaluated either way, all we are doing is
turning off the default echoing of the expression result (and the
side-effect of assigning the expression result to the underscore
> It just so happens that the eval of a quoted string returns
> itself whereas "some expression with %s" % "substitution"
> would actually evaluate to non-echo.
What the normal displayhook does is echo the result of non-None
expressions, and assign those to _. What the little hack I showed
did is replace that default behaviour with a no-op, a do-nothing.
Whether this is a good idea or not is a different matter, but let's
be clear about what's happening.
> kirby at dell:~$ python ./repl.py
>>>> 'THIS IS A STRING'
> THIS IS A STRING
>>>> [x*x for x in range(10)]
> [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
>>>> "1-2-3 %s" % "testing"
> 1-2-3 testing
> Would one turn off all of the above, or just the first eval-print?
Not sure what you're asking. None of the evals are being changed,
just the default echoing. If you then want to print you could either
assign it to a variable and print that, or pass the whole expression
through print. Again, I'm not saying this is a good thing, but it is
more consistent with how the non-interactive runtime works.
> What would be the point of a broken shell, vs explaining that
> Python, like many languages, features a REPL (read-eval-print loop)?
Well, it might be useful to show learners that a) this is different
from what you should expect when you run your program, and b) it is
not magic. For instance:
>>> 'my name is %s' % 'Dethe'
'my name is Dethe'
>>> import sys
>>> def noecho(value): pass
>>> def echo(value):
... print value
>>> def echo_and_assign(value):
... print value
... global _
... _ = value
>>> sys.displayhook = noecho
>>> sys.displayhook = echo
<built-in function displayhook>
>>> sys.displayhook = echo_and_assign
Now we've re-implemented the default behaviour (modulo any edge cases
it handles that I've missed). And if we want to completely get back
to the default, after playing around with the displayhook, that's
>>> sys.displayhook = sys.__displayhook__ # always returns
displayhook back to system default
Or if we want something to happen every time we eval a line in the
>>> def enhanced_display(value):
>>> sys.displayhook = enhanced_display
It's all fun and games, until someone loses their ribs. ;-)
Language is what something becomes when you think in it -- Robert
More information about the Edu-sig